Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

asp.net core with microservices

$
0
0

I'd like to create a web app using .NET Core and Microservices and either use SQL or MongoDB as the datastore. Is something like this doable? Are there any good complete tutorials out there on something like this, or do I have to find separate tutorials on each and then put them together? I want the app do to CRUB operations with security and host on IIS.

(I have a lot of time on my hands and looking to learn something new)


JWT token validation

$
0
0

Hi,

I need to validate multiple token that I receive in same request, I followed below code flow

services.AddAuthentication()
        .AddJwtBearer("Token1", options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidIssuer = Issuer,
                ValidateAudience = true,
                ValidAudience = Audience,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key)),
            };
            options.Events = new JwtBearerEvents()
            {
                OnMessageReceived = context =>
                {
                    var Token = context.Request.Headers["UserCred1"].ToString();
                    context.Token = Token;
                    return Task.CompletedTask;
                },
            };
        })
        .AddJwtBearer("Token2", options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidIssuer = Issuer,
                ValidateAudience = true,
                ValidAudience = Audience,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key)),
            };
            options.Events = new JwtBearerEvents()
            {
                OnMessageReceived = context =>
                {
                    var Token = context.Request.Headers["UserCred2"].ToString();
                    context.Token = Token;
                    return Task.CompletedTask;
                },
            };
        });
    services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes("Token1", "Token2")
        .Build();
    });

Above code works as OR condition, like either Token1 or Token 2 authentication is valid then returns as Success. But for me I need to consider success only when both "Token1"AND, "Token2" are valid. 

Kindly let me know your thoughts..

Net Core 3 Identity

$
0
0

Hey everyone. I'm new to asp net core and i need some help. I scaffolded the Identity into my  web form razor project. The database name is ProiectLicenta where i can see all the Indentity tables. Basically what i am trying to do is if anyone registers i want their usernames and emails from the AspNetUsers table listed in another page called userlist. That table on the userlist has to update everytime a new person registers. Is it posible?

Trying to get my head around different ways of using Razor Pages

$
0
0

Correct me if Im wrong, but since Razor Pages and their handler methods generally return a viewmodel, the whole page needs to refresh to handle this.  So there are different ways of setting up a razor page, much like there are with a MVC application.  Some of them are

- Handler methods.  Each method returns a model
- Named handler methods.  Each handler method is referenced via seperate form tag from within the razor page
- Partial pages
- Partial pages with Ajax, which lets you update sections of a page without refreshing the whole page
- Using a separate web api combined with jQuery to fetch data and update sections of a page. 

That about sum it up?  Please correct where Im wrong.

How i can restrict the Authorize attribute to certain users only, inside my asp.net core mvc web application

$
0
0

I have created a new asp.net MVC core web application and i set it to use organizational account as follow:-enter image description here

now if i add [Authorize] attribute to an action method then the user will be asked to login first. but my question is how i can only allow certain users to access the action method?

second question, is how i can prevent users from logging to the application unless they are inside a predefined list?

An unhandled exception occurred while processing the request. SqlException: Invalid object name 'Question'. Microsoft.Data.SqlClient.SqlCommand+c.b__164_0(Task result)

$
0
0

I am working on an asp.net core mvc, and i use this command to map a database tables:-

PM>  Scaffold-DbContext "Server=(localdb)\ProjectsV13;Database=LandingPage;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Build started...
Build succeeded.
The EF Core tools version '3.1.0' is older than that of the runtime '3.1.3'. Update the tools for the latest features and bug fixes.   

then i create a new controller class, and when i access the controller i got this exception:-

An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'Question'.
Microsoft.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__164_0(Task<SqlDataReader> result)
Stack Query Cookies Headers Routing 
SqlException: Invalid object name 'Question'.
Microsoft.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__164_0(Task<SqlDataReader> result)
System.Threading.Tasks.ContinuationResultTaskFromResultTask<TAntecedentResult, TResult>.InnerInvoke()
System.Threading.Tasks.Task+<>c.<.cctor>b__274_0(object obj)
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot, Thread threadPoolThread)
Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+AsyncEnumerator.InitializeReaderAsync(DbContext _, bool result, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync<TState, TResult>(TState state, Func<DbContext, TState, CancellationToken, Task<TResult>> operation, Func<DbContext, TState, CancellationToken, Task<ExecutionResult<TResult>>> verifySucceeded, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+AsyncEnumerator.MoveNextAsync()
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
LandingPageFinal3.Controllers.QuestionsController.Index() in QuestionsController.cs+
            return View(await landingPageContext.ToListAsync());
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Can anyone advice on this please?

How my web api handle multiple clients?

$
0
0

Hi

I have a problem that i have a camera device and i built a web application to it. it consists of an angular app and asp.net core web api and a normal c# .net core desktop app that the client will install to control the camera in his machine. this camera takes face image and process it and send a code to web api with the info to authenticate the user.

the problem is as follows:

1 - When i used static variables in web api so the c# .net core app can speak to angular app and vice versa through this static variables in web api it couldn't handle multiple users as if one user change this static variable the changes appears in the other users which in turn control their cameras and i want the only user who change the variable sees it and only control his camera.

2 - I tried to use sessions but the problem that if the angular app sets the session and if the c# .net core app try to get this session it always be null as if there is no session being set

3 - The closest approch to use a dictionary for a user who enters the website and store the variable in this dictionary but i don't know how to get a unique info for the user so i can put it in the dictionary and sync it with the c# .net core desktop app.

4 - Some suggested to authenticate the user and i will get the info of this user as JWT token the problem is happening at authentication the authentication should happen with the camera.

5 - When a user open the angular and web api in the browser if there is other users running the destop app and this user click on open camera in the browser it opens the camera on all other users which is a big problem i want this user to open the camera on his machine only.

Hint: the angular app and web api will be on one application on the server and the c# .net core desktop app will be on the client machine to control his camera so how to sync between the desktop application in this user machine and the angular app and web api he accesses through the browser.

InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.

$
0
0

I have a database named "LandingPage", and using this command i have mapped the database tables inside my asp.net mvc core:-

 Scaffold-DbContext "Server=(localdb)\ProjectsV13;Database=LandingPage;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Then i added a controller and chose one of the models, but when i try access the controller i got this exception inside the web browser:-

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Stack Query Cookies Headers Routing 
InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

any advice


Add items to a list from view model

$
0
0

Hey how's it going,

I'm working on a deck builder for a card game. My rough build is up on https://chronoclashdeckbuilder.azurewebsites.net/DeckBuilder and I have the project on my github https://github.com/Zami77/ChronoClashDeckBuilder

The idea is to click the images that are on the deck builder page and have them be dynamically added to a list. Once the list is complete I could then have it be saved to my SQL database tied to a user account. I'm focusing just on one step at a time, and I'd like to be able to dynamically add and remove cards from the list and have them be displayed to the user. I'll post what I think are the relevant code sections, but if it feels something is missing please check out my github. Thanks in advance for any help!

DeckBuilder View Index.cshtml

@model ChronoClashDeckBuilder.Models.ViewModels.DeckBuilderListViewModel

@{
    ViewData["Title"] = "Deck Builder";
}<h1>Deck Builder!</h1><p>Still have to implement picking a card and adding to deck.</p><p><a class="badge-dark" asp-area="" asp-controller="DeckBuilder" asp-action="Index" asp-route-curDeck="@Model.NewDeck">Display Deck</a></p><tbody>
    @foreach (var item in Model.NewDeck)
    {<tr><td>
                @item.CardName</td></tr>
    }</tbody><tbody>
    @foreach (var item in Model.Cards)
    {<tr><td><input type="image" src="~/Images/Chrono Clash Card Images/Naruto Set 1/@item.CardImage"
                       alt="@item.CardName"
                       style="width:136px;height:185px;" />
                @*How to add from viewlist to razor page, check javascript
                asp-action="@model.newdeck.add(item)"*@</td></tr>
    }</tbody>

DeckBuilderController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChronoClashDeckBuilder.Models;
using Microsoft.AspNetCore.Mvc;

namespace ChronoClashDeckBuilder.Controllers
{
    public class DeckBuilderController : Controller
    {
        private ICardRepository repository;
        public DeckBuilderController(ICardRepository repo)
        {
            repository = repo;
        }
        public IActionResult Index(List<Card> curDeck, Card cardToAdd)
        {
            if (cardToAdd != null)
                curDeck.Add(cardToAdd);

            return View(new Models.ViewModels.DeckBuilderListViewModel
            {
                Cards = repository.Cards,
                NewDeck = curDeck
            });
        }
    }
}

Models Card.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ChronoClashDeckBuilder.Models
{
    public partial class Card
    {
        [Key]
        [StringLength(20)]
        public string CardNumber { get; set; }
        [StringLength(20)]
        public string CardSet { get; set; }
        [StringLength(20)]
        public string CardType { get; set; }
        [StringLength(100)]
        public string CardImage { get; set; }
        [StringLength(10)]
        public string CardColor { get; set; }
        public int? CardCost { get; set; }
        public int? CardStrength { get; set; }
        [StringLength(80)]
        public string CardName { get; set; }
        [StringLength(200)]
        public string CardAbilities { get; set; }
        [StringLength(200)]
        public string CardStackAbilities { get; set; }
    }
}

ViewModels DeckBuilderListViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ChronoClashDeckBuilder.Models.ViewModels
{
    public class DeckBuilderListViewModel
    {
        public IEnumerable<Card> Cards { get; set; }
        public List<Card> NewDeck { get; set; }
    }
}

System.AggregateException:

$
0
0

Below is the error that I am getting in program cs. I am using aspnet core mvc 3.1

 Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole] Lifetime: Scoped ImplementationType: 

Here is the program:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace Bumples15
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();  //here is where they say the problem is.
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

}
}

Below is the startup page

using Bumples15.Models;
using Bumples15.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace Bumples15
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

services.AddControllersWithViews();

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();

services.AddScoped<RoleManager<IdentityRole>>();
services.AddScoped<IRepository<Product>, SqlBooksRepository>();
services.AddScoped<IRepository<Order>, SqlOrdersRepository>();

services.AddRazorPages();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();

}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}

The course that I am using is a 2.1 program but I have tried to update it to 3.1. Where am I going wrong,

Thanks,

Jen

How can i run .net core app with Visual Studio 2017 ?

$
0
0

Hi I have a .net core app in VS 2017, but get the following error , 

Error NETSDK1045 The current .NET SDK does not support targeting .NET Core 3.1.  Either target .NET Core 2.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1.

If i change to a lower version of .net core like .net core 2.1 , i get errors because some features are not supported by the earlier version of .net core .

How can i fix this ?

How can i test a Microservice ?

$
0
0

Hi ,

Im new to microservices and Ive been given a microservice written in .net core 3.1.

How do i start to test it and check if it is working and its functionality ?

Thanks

Is generated code sanitized

$
0
0

Untouched generated code here:

@page
@model pcore31.AddpetModel

@{
    Layout = null;
}

<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Addpet</title></head><body><h4>Pet</h4><hr /><div class="row"><div class="col-md-4"><form method="post"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Pet.PetName" class="control-label"></label><input asp-for="Pet.PetName" class="form-control" /><span asp-validation-for="Pet.PetName" class="text-danger"></span></div><div class="form-group"><label asp-for="Pet.Dogpic" class="control-label"></label><input asp-for="Pet.Dogpic" class="form-control" /><span asp-validation-for="Pet.Dogpic" class="text-danger"></span></div><div class="form-group"><label asp-for="Pet.Odate" class="control-label"></label><input asp-for="Pet.Odate" class="form-control" /><span asp-validation-for="Pet.Odate" class="text-danger"></span></div><div class="form-group form-check"><label class="form-check-label"><input class="form-check-input" asp-for="Pet.Ocheck" /> @Html.DisplayNameFor(model => model.Pet.Ocheck)</label></div><div class="form-group"><input type="submit" value="Create" class="btn btn-primary" /></div></form></div></div><div><a asp-page="Index">Back to List</a></div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}</body></html>

Take for example this line:

<input asp-for="Pet.PetName" class="form-control" />

Is that asp-for also appling the equal to htmlentities?  Or will I have to modify the code and do that myself.

A search I got punching in "<input asp-for" yielded  https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1

I searched that page for "encode", "entity", "enti", "santi", "sanitize.  No hits at all.

So if the generated pages doesn't sanitize data, why are they used?  I normally sanitize the request, but again if I have to sanitize each field, why the auto context instead of individual request?

For example:

string petname = Request.Form["petname"];
// I could add a custom sanitize class

string petname =  Helper.sanitize(Request.Form["petname"]);

// Something like that.

Sorry this "generated" code still confuses me.

Dotnet Core calling a soap service issue

$
0
0

I have a dotnet core 2.0 app which makes some calls out to some 3rd party soap services. The web references have been added to the project using a wsdl and connected services. Everything works fine but periodically it stops working and throws an error.

Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

System.TypeLoadException: Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

at SoapClient.GetDetailsAsync(GetDetailsRequest request) in Connected Services\SoapClient\Reference.cs:line 1146

This api runs on linux container and when i restart the api the error goes away and everything runs fine. There is no issue on the service side because the method it calls exists. Web reference has been updated to the latest. There is no outgoing call from the api when this error occurs.

Any help in debugging or fixing this issue?

Thanks

can I access the "/Identity/Account/Login" & "/Identity/Account/Register/" action methods and Controller inside my asp.net core MVC

$
0
0

I have created an asp.net MVC core web application which uses individual accounts, as follow:-enter image description here

where i got a predefined Register and login logic (actions methods and Views such as /Identity/Account/Login & /Identity/Account/Register/), but i can not access the related controller classes and views,, so is it possible to access and modify the built-in registration and logging logic?


Problem accessing ViewContext.RouteData inside my Razor view when i access the asp.net core identity view

$
0
0

I have added the following inside my _layout view inside my Asp.net MVC core web application:-

    @if (ViewContext!= null && ViewContext.RouteData != null && (ViewContext.RouteData.Values["controller"].ToString().ToLower() == "home" && ViewContext.RouteData.Values["action"].ToString().ToLower() == "faq"))

to show certain sections only when the user access /Home/FAQ/, this will work well for all the controller. but when i access any of the Identity built-in view such as "**/Identity/Account/Login**" & "**/Identity/Account/Register/**" i will get this error:-

    NullReferenceException: Object reference not set to an instance of an object.
    AspNetCore.Views_Shared__Layout.<ExecuteAsync>b__66_1() in _Layout.cshtml+
                    @if (ViewContext!= null && ViewContext.RouteData != null && (ViewContext.RouteData.Values["controller"].ToString().ToLower() == "home" && ViewContext.RouteData.Values["action"].ToString().ToLower() == "faq"))
    Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
    AspNetCore.Views_Shared__Layout.ExecuteAsync()
    Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
    Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
    Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderLayoutAsync(ViewContext context, ViewBufferTextWriter bodyWriter)
    Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
    Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
    Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
    Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
    Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

csproj is not using latest C# version in VS 2019

$
0
0

I had upgraded the solution/projects to VS 2019 & .NET Core in all projects to netcoreapp3.1 & netstandard1.2 .  When compiled WebApp csproj is still showing older version because of this compiler error message "Program does not contain a static Main method suitable for an entry point".  I'm using async which is now permitted in C# version 8 & up.  I even try LangVersion as latest or preview w/ no luck, I read documentation that we don't need to specify LangVersion starting with .NET Core 3.0 & up as it will be done automatically.  So what could be the problem here?

[ Program.cs ]

    public class Program

    {

        public async static void Main(string[] args)

        {

            await Host.CreateDefaultBuilder(args)

                .ConfigureWebHostDefaults(webBuilder => {

                    webBuilder.UseContentRoot(Directory.GetCurrentDirectory());

                    webBuilder.UseKestrel();

                    webBuilder.UseAzureAppServices();

                    webBuilder.UseStartup<Startup>();

                    //webBuilder.UseSerilog()

                })

            .ConfigureLogging((logging) =>

            {

                //logging.AddSerilog();

            })

            .Build()

            .RunAsync();

        }

    }

[ csproj ]

    <Project Sdk="Microsoft.NET.Sdk.Web">

      <PropertyGroup>

        <VersionPrefix>1.2.0</VersionPrefix>

        <OutputType>Exe</OutputType>

        <TargetFramework>netcoreapp3.1</TargetFramework>

        <PreserveCompilationContext>true</PreserveCompilationContext>

        <AssemblyName>ABCoA.Payments.CustomerWeb</AssemblyName>

        <PackageId>ABCoA.Payments.CustomerWeb</PackageId>

      </PropertyGroup>

      <PropertyGroup>

        <LangVersion>preview</LangVersion>

      </PropertyGroup>

    </Project>

Bundling my CSS files is not working

$
0
0

Inside my _Layout view i have the following css definitions:-

<link rel="stylesheet" href="~/css/bootstrap.min.css"><link rel="stylesheet" href="~/css/owl.carousel.min.css"><link rel="stylesheet" href="~/css/magnific-popup.css"><link rel="stylesheet" href="~/css/font-awesome.min.css"><link rel="stylesheet" href="~/css/themify-icons.css"><link rel="stylesheet" href="~/css/nice-select.css"><link rel="stylesheet" href="~/css/flaticon.css"><link rel="stylesheet" href="~/css/gijgo.css"><link rel="stylesheet" href="~/css/animate.css"><link rel="stylesheet" href="~/css/slick.css"><link rel="stylesheet" href="~/css/slicknav.css"><link rel="stylesheet" href="~/css/jquery-ui.css"><link rel="stylesheet" href="~/css/style.css"><link rel="stylesheet" href="~/css/site.css">

so i bundle them as follow:-

[
  {"outputFileName": "wwwroot/css/site5.min.css","inputFiles": ["wwwroot/css/site.css","~/css/bootstrap.min.css","~/css/owl.carousel.min.css","~/css/magnific-popup.css","~/css/font-awesome.min.css","~/css/themify-icons.css","~/css/nice-select.css","~/css/flaticon.css","~/css/gijgo.css","~/css/animate.css","~/css/slick.css","~/css/slicknav.css","~/css/jquery-ui.css","~/css/style.css","~/css/site.css"



    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js","inputFiles": ["wwwroot/js/site.js"
    ],"minify": {"enabled": true,"renameLocals": true
    },"sourceMap": false
  }
]

and i replace all the css definitions with one definition as follow:-

<link rel="stylesheet" href="wwwroot/css/site5.min.css">

but i lost all the css effect on my site.. so seems the bundle is not working fine... any advice?

Guidelines and Steps to Package an ASP .NET Core WEB API

$
0
0

Greetings,

        I have created my first .NET Core Web API that will be sent to another site to be installed.  I've searched the web but I cannot find any definitive guidelines and steps to properly package the Web API into an installer that can be given to the other site to use to install it on their system.   

        Most articles assume the Web API was developed at the same location as the web server so they go into detail on how to publish to it.  I have found very little valid information for actually packaging a web API and installing/publishing it using the installer created.

        Can someone please provide information on how to properly package an ASP .NET Core Web API so it can be installed at another site?  It can be either instructions for MSI or MSIX.  I created the Web API using ASP .NET Core 2.1 and Visual Studio 2017.

Thanks

A View that uses multiple models breaks asp-for tag helper

$
0
0

I have a View that lets users update a 'links' table, linking a person to an object, in this case an air sickness bag (yes, really).  Because of this, I pass the following data model to my view:

public class LinkViewModel
{
public Bagsmvc Bag { get; set; }
public Linksmvccore Link { get; set; }
public List<SelectListItem> Options { get; set; } // to generate a drop-down list of people
}

All I want to do is match a person (from Options drop down) to a bag and put the results in Link,  Here's the view

@model BagContext.LinkViewModel

<form asp-action="Create">
  <div class="form-group">
    <input asp-for="@Model.Link.BagId" value="@Model.Bag.Id" class="form-control" readonly="@(true)" />
    @*<input id="BagId" name="BagId" value="@Model.Bag.Id" class="form-control" readonly="@(true)"/>*@
  </div>
  <div class="form-group">
    <select name="PersonID" asp-items="@Model.Options" onchage=""></select>
  </div>
  <div class="form-group">
    <input type="submit" value="Create" class="btn btn-primary" />
  </div>
</form>

And this is how the form is submitted to the controller.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("LinkNumber,BagId,PersonId")] Linksmvccore linksmvccore)

This does not work because Core tries to match up Link.BagId with BagId and can't do it.  The line I commented out in the Viewdoes work, but why use tag helpers at all if I'm just going to hard code 'magical strings' into the code?  In fact, Binding itself uses these magical strings too. 

What am I missing here that would allow me to use the tag-helpers properly?  How can I get this to work?

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>