Ошибка an unhandled exception occurred while processing the request

So, I’m trying to implement OpenIddict version 1.0.0-beta2-0580 with NET core 1.1 and I get the following error:

An unhandled exception occurred while processing the request

This is based on this : https://github.com/openiddict/openiddict-core/tree/dev/samples

Connect rest call

The db registers the database correctly, the settings is loaded and everything works here. The tables in the db: __efmigrationshistory, aspnetroleclaims, aspnetroles, aspnetuserclaims, aspnetuserlogins, aspnetuserroles, aspnetusers, aspnetusertokens, basetransaction, openiddictapplications, openiddictauthorizations, openiddictscopes, openiddicttokens

And then I have the following stack trace :

InvalidOperationException: The authentication ticket was rejected because the mandatory subject claim was missing.
AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerHandler+<HandleSignInAsync>d__5.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Authentication.AuthenticationHandler+<SignInAsync>d__66.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager+<SignInAsync>d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.SignInResult+<ExecuteResultAsync>d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeResultAsync>d__30.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResultFilterAsync>d__28.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware+<ExecuteWithFilter>d__7.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

In the startup I have :

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

    services.RegisterDatabase(aspNet: true, useOpenIddict : true);

    // Register the Identity services.
    service.AddIdentity<User, IdentityRole>(config => { config.SignIn.RequireConfirmedEmail = requireConfirmEmail; })
          .AddEntityFrameworkStores<DatabaseContext>()
          .AddDefaultTokenProviders();

    services.AddOpenIddict(options =>
    {
        // Register the Entity Framework stores.
        options.AddEntityFrameworkCoreStores<DatabaseContext>();

        // Register the ASP.NET Core MVC binder used by OpenIddict.
        // Note: if you don't call this method, you won't be able to
        // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
        options.AddMvcBinders();

        // Enable the token endpoint.
        options.EnableTokenEndpoint("/connect/token");

        // Enable the password flow.
        options.AllowPasswordFlow();

        // During development, you can disable the HTTPS requirement.
        options.DisableHttpsRequirement();

        // Note: to use JWT access tokens instead of the default
        // encrypted format, the following lines are required:
        //
        // options.UseJsonWebTokens();
        // options.AddEphemeralSigningKey();
    });
}

And then at the configure I have this :

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IServiceProvider service, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseOpenIddict();

    // Create a new service scope to ensure the database context is correctly disposed when this methods returns.
    using (var scope = service.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<DatabaseContext>();

        await context.Database.MigrateAsync();

        OpenIddictApplicationManager<OpenIddictApplication> manager = scope.ServiceProvider.GetRequiredService<OpenIddictApplicationManager<OpenIddictApplication>>();

        // ---- Delete code comment ----------
        // To test this sample with Postman, use the following settings:
        //
        // * Authorization URL: http://localhost:54540/connect/authorize
        // * Access token URL: http://localhost:54540/connect/token
        // * Client ID: postman
        // * Client secret: [blank] (not used with public clients)
        // * Scope: openid email profile roles
        // * Grant type: authorization code
        // * Request access token locally: yes
        var client = await manager.FindByClientIdAsync("postman", cancellationToken); 

        if (client == null)
        {
            var application = new OpenIddictApplication
            {
                ClientId = "postman",
                DisplayName = "Postman",
            };
            await manager.CreateAsync(application, cancellationToken);
        }
    }


    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Then the auth controllers look like this:

public class AuthorizationController : Controller
{
    private readonly SignInManager<User> _signInManager;
    private readonly UserManager<User> _userManager;

    public AuthorizationController(
        SignInManager<User> signInManager,
        UserManager<User> userManager)
    {
        _signInManager = signInManager;
        _userManager = userManager;
    }

    [HttpPost("~/connect/token"), Produces("application/json")]
    public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
    {
        Debug.Assert(request.IsTokenRequest(),
            "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
            "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

        if (request.IsPasswordGrantType())
        {
            var user = await _userManager.FindByNameAsync(request.Username);
            if (user == null)
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The username/password couple is invalid."
                });
            }

            // Ensure the user is allowed to sign in.
            if (!await _signInManager.CanSignInAsync(user))
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The specified user is not allowed to sign in."
                });
            }

            // Reject the token request if two-factor authentication has been enabled by the user.
            if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user))
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The specified user is not allowed to sign in."
                });
            }

            // Ensure the user is not already locked out.
            if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The username/password couple is invalid."
                });
            }

            // Ensure the password is valid.
            if (!await _userManager.CheckPasswordAsync(user, request.Password))
            {
                if (_userManager.SupportsUserLockout)
                {
                    await _userManager.AccessFailedAsync(user);
                }

                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The username/password couple is invalid."
                });
            }

            if (_userManager.SupportsUserLockout)
            {
                await _userManager.ResetAccessFailedCountAsync(user);
            }

            // Create a new authentication ticket.
            var ticket = await CreateTicketAsync(request, user);

            return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
        }

        return BadRequest(new OpenIdConnectResponse
        {
            Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
            ErrorDescription = "The specified grant type is not supported."
        });
    }

    private async Task<AuthenticationTicket> CreateTicketAsync(OpenIdConnectRequest request, User user)
    {
        // Create a new ClaimsPrincipal containing the claims that
        // will be used to create an id_token, a token or a code.
        var principal = await _signInManager.CreateUserPrincipalAsync(user);

        // Note: by default, claims are NOT automatically included in the access and identity tokens.
        // To allow OpenIddict to serialize them, you must attach them a destination, that specifies
        // whether they should be included in access tokens, in identity tokens or in both.

        foreach (var claim in principal.Claims)
        {
            // In this sample, every claim is serialized in both the access and the identity tokens.
            // In a real world application, you'd probably want to exclude confidential claims
            // or apply a claims policy based on the scopes requested by the client application.
            claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);
        }

        // Create a new authentication ticket holding the user identity.
        var ticket = new AuthenticationTicket(
            principal, new AuthenticationProperties(),
            OpenIdConnectServerDefaults.AuthenticationScheme);

        // Set the list of scopes granted to the client application.
        // Note: the offline_access scope must be granted
        // to allow OpenIddict to return a refresh token.
        ticket.SetScopes(new[]
        {
            OpenIdConnectConstants.Scopes.OpenId,
            OpenIdConnectConstants.Scopes.Email,
            OpenIdConnectConstants.Scopes.Profile,
            OpenIdConnectConstants.Scopes.OfflineAccess,
            OpenIddictConstants.Scopes.Roles
        }.Intersect(request.GetScopes()));

        return ticket;
    }
}

The dependencies :

<PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="1.1.0" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="1.1.2" />
    <PackageReference Include="OpenIddict" Version="1.0.0-beta2-0615" />
    <PackageReference Include="OpenIddict.EntityFrameworkCore" Version="1.0.0-beta2-0615" />
    <PackageReference Include="OpenIddict.Mvc" Version="1.0.0-beta2-0615" />

  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.1" />
  </ItemGroup>

  • Remove From My Forums
  • Question

  • User-190697402 posted

    Hi ,

    Im getting this error after trying to add Assets to StaffAssets table

    InvalidOperationException: The instance of entity type 'StaffAssets' cannot be tracked because another instance with the same key value for {'StaffID'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

    Here is what i have to acheive, My Assets tab will have Create New button,when i click on that it should navigate to Add Screen,

    I should be able to add the assets for the employee

    I should be able to add multiple Assets.Whats happening now is,when i add assets for the first its inserting record to StaffAssets table,but when im adding it for the second time,im getting the above mentioned error.

Answers

  • User1312693872 posted

    Hi,teenajohn1989

    If your problem is save the input data but show the last input data, then I have reproduced it.

    You just need to put the query sentence into ‘if’ method, like my demo:

    public async Task<IActionResult> OnPostInsertAssetsDetailsAsync(int current = 3)
            {
                if (ModelState.GetFieldValidationState("StaffAssets") == ModelValidationState.Valid)
                {
                    await _context.StaffAssets.AddAsync(StaffAssets);
                    await _context.SaveChangesAsync();
                    //when add works, then +1 ,means next tab
                    currentTab = current;
                    TempData["EmpID"] = StaffAssets.EmpID;
                    TempData["StaffID"] = StaffAssets.StaffID;
                    ShowStaffAssets = _context.StaffAssets.Where(c => c.StaffAssetName == StaffAssets.StaffAssetName).AsNoTracking().ToList();
                    return Page();
                }
                else
                {
                    var errors = ModelState.Values.SelectMany(v => v.Errors);
                    return Page();
                }
            }

    Result:

    Best Regards,

    Jerry Cai

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User1312693872 posted

    Hi,teenajohn1989

    What is ‘not populate the already inserted one’ while you want to show all the added data means?

    If you want to show all the assets, you just need to change the query in my demo to yours :

    ShowStaffAssets = _context.StaffAssets.Where(c => c.StaffID == StaffAssets.StaffID).ToList();

    Result:

    If anything still wrong , you can share your create method, I’m not sure what you did in it.

    <input type="button" class="btn-success" id="OnClickCreateStaffAsset" value="Create New" />

    Best Regards,

    Jerry Cai

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

  • User-190697402 posted

    Hi Jerry Cai,

    The display issue is fixed now.what i did is just add AsNoTracking() in the query 

    ShowStaffAssets =  _context.StaffAssets.Where(c => c.StaffID == StaffAssets.StaffID).OrderBy(c => c.StaffAssetName).AsNoTracking().ToList();
                   

    Thank you so much for the endless support and letting me know how to debug the LINQ query also. 

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

Describe the bug

After adding another Asp.Net Core WebApi project to a Blazor WebAssembly Hosted solution, and adding [Authorize] attribute to a controller, the new WebApi project fails to start with:
An unhandled exception occurred while processing the request.
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)

To Reproduce

  1. Create a new Blazor WebAssembly project
  2. Change Authentication to ‘Individual User Accounts’ and select ‘Store user accounts in-app’
  3. Make sure ASP.Net Core hosted is checked (true)
  4. Run update-database in Package Manager Console to add the Asp.net Identity and IdentityServer4 tables
  5. Register an account
  6. Add a new Asp.Net Core WebApi project to the solution
  7. Add [Authorize] attribute to WeatherForecast controller
  8. Add CORS and allow the Client origin
  9. Add authentication and authorization
    ` services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme);
    //services.AddAuthentication(options =>
    //{
    // options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    // options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    //});
    services.AddAuthorization();

        app.UseAuthentication();
        app.UseAuthorization();

`
10) Back in the Client project make a copy of Fetch.razor
11) In the copy of Fetch.razor inject or create a new HttpClient that has the base address of the new WebApiProject
12) Build and run the new WebApi project and get error:
An unhandled exception occurred while processing the request.
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)

Tried:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme);
and
services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; });
with same exception.

What is required to configure additional WebApi projects for the new IdentityServer4 / Asp.Net Identity authentication / authorization?

Exceptions (if any)

An unhandled exception occurred while processing the request.
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)

Further technical details

  • ASP.NET Core version 3.1
  • Include the output of dotnet --info
    PS C:UsersRoy> dotnet —info
    .NET Core SDK (reflecting any global.json):
    Version: 3.1.400-preview-015151
    Commit: 0755a9e324

Runtime Environment:
OS Name: Windows
OS Version: 10.0.18363
OS Platform: Windows
RID: win10-x64
Base Path: C:Program Filesdotnetsdk3.1.400-preview-015151

Host (useful for support):
Version: 3.1.5
Commit: 65cd789777

.NET Core SDKs installed:
1.0.0-preview2-003131 [C:Program Filesdotnetsdk]
1.0.4 [C:Program Filesdotnetsdk]
2.1.4 [C:Program Filesdotnetsdk]
2.1.101 [C:Program Filesdotnetsdk]
2.1.102 [C:Program Filesdotnetsdk]
2.1.201 [C:Program Filesdotnetsdk]
2.1.202 [C:Program Filesdotnetsdk]
2.1.401 [C:Program Filesdotnetsdk]
2.1.504 [C:Program Filesdotnetsdk]
2.1.505 [C:Program Filesdotnetsdk]
2.1.507 [C:Program Filesdotnetsdk]
2.1.509 [C:Program Filesdotnetsdk]
2.1.512 [C:Program Filesdotnetsdk]
2.1.602 [C:Program Filesdotnetsdk]
2.1.700 [C:Program Filesdotnetsdk]
2.2.203 [C:Program Filesdotnetsdk]
3.1.300 [C:Program Filesdotnetsdk]
3.1.301 [C:Program Filesdotnetsdk]
3.1.400-preview-015151 [C:Program Filesdotnetsdk]

.NET Core runtimes installed:
Microsoft.AspNetCore.All 2.1.2 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.1.8 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.1.9 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.1.11 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.1.13 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.1.16 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.1.19 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.All 2.2.4 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.2 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.1.8 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.1.9 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.1.11 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.1.13 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.1.16 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.1.19 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 2.2.4 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.2 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.4 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.5 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.NETCore.App 1.0.1 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 1.0.5 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 1.1.2 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.0.5 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.0.6 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.0.7 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.0.9 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.1.3-servicing-26724-03 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.1.8 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.1.9 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.1.11 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.1.13 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.1.16 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.1.19 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 2.2.4 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 3.1.2 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 3.1.4 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 3.1.5 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.1.2 [C:Program FilesdotnetsharedMicrosoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 3.1.4 [C:Program FilesdotnetsharedMicrosoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 3.1.5 [C:Program FilesdotnetsharedMicrosoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
PS C:UsersRoy>

  • The IDE (VS / VS Code/ VS4Mac) you’re running on, and it’s version
    VS 2019 16.6.2 on Windows 10

Я изучал возможности использования сборок в Asp.net core и наткнулся на одну проблему. При попытке вызвать метод точки входа в приложение, использующее контекст данных для связи с БД выкидывает ошибку. Контекст оформлен как сервис.

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type ‘TestMVC1.Models.MobileContext’ while attempting to activate ‘TestMVC1.Controllers.HomeController’.
InvalidOperationException: Unable to resolve service for type ‘TestMVC1.Models.MobileContext’ while attempting to activate ‘TestMVC1.Controllers.HomeController’.
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.b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Как правильно использовать БД внутри загружаемой сборки?
Загрузка сборки

public void ConfigureServices(IServiceCollection services)
        {
            executableLocation = Assembly.GetEntryAssembly().Location;
            var path = Path.Combine(Path.GetDirectoryName(executableLocation), "Plugins");
            var assemblies = Directory
                    .GetFiles(path, "*.dll", SearchOption.AllDirectories)
                    .Select(AssemblyLoadContext.Default.LoadFromAssemblyPath)
                    .ToList();
            path = Path.Combine(path, "TestMVC1.dll");
            var alc = new TestAssemblyLoadContex();
            Assembly a = alc.LoadFromAssemblyPath(path);
            var b = a.GetTypes();
            services.AddMvc().AddApplicationPart(a).AddRazorOptions(
            o =>
            {
                o.FileProviders.Add(new EmbeddedFileProvider(a, a.GetName().Name));
            }
            );
            a.EntryPoint.Invoke(null, new Object[] { null });
        }

Использование сервиса с контекстом БД

private MobileContext db;
        public HomeController(MobileContext context)
        {
            db = context;
        }

Контекст данных

public class MobileContext : DbContext
    {
        public DbSet<Phone> Phones { get; set; }
        public MobileContext(DbContextOptions<MobileContext> options)
            : base(options)
        {
            Database.EnsureCreated();
        }
    }

Recently, I came across an interesting problem. Whenever we run my ASP.NET Core application in Development environment, I get the below exception.

Details about the setup:

The below template was used:

Angular project template with ASP.NET core — https://docs.microsoft.com/en-us/aspnet/core/client-side/spa/angular?view=aspnetcore-2.2&tabs=visual… along with AAD integration.

When we publish this application in Azure App Service, it works fine. But when we run the same application in Visual Studio, it fails with the below error.

CaptureError.JPG

An unhandled exception occurred while processing the request.IOException: The server returned an invalid or unrecognized response.
System.Net.Http.HttpConnection.FillAsync()HttpRequestException: An error occurred while sending the request.
System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)HttpRequestException: Failed to proxy the request to http://localhost:54232/, because the request to the proxy target failed. Check that the proxy target server is running and accepting requests to http://localhost:54232/.The underlying exception message was 'An error occurred while sending the request.'.Check the InnerException for more details.
Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task<Uri> baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s)·      Stack 
·      Query 
·      Cookies 
·      Headers

IOException: The server returned an invalid or unrecognized response.

System.Net.Http.HttpConnection.FillAsync()
System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(bool foldedHeadersAllowed)
System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)Show raw exception details

HttpRequestException: An error occurred while sending the request.

System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task<Uri> baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s)Show raw exception details

HttpRequestException: Failed to proxy the request to http://localhost:54232/, because the request to the proxy target failed. Check that the proxy target server is running and accepting requests to http://localhost:54232/. The underlying exception message was 'An error occurred while sending the request.'.Check the InnerException for more details.

Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task<Uri> baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s)
Microsoft.AspNetCore.Builder.SpaProxyingExtensions+<>c__DisplayClass2_0+<<UseProxyToSpaDevelopmentServer>b__0>d.MoveNext()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)Show raw exception details

It took almost a whole day for me to narrow down the problem:

  • The AAD auth settings and configurations both in the azure portal as well as the app is correct.
  • The auth flow is same between the working and non-working scenarios.
  • We compared the headers, cookies, tokens etc. very closely between working and non-working cases and nothing is different.
  • We captured the log statement from the .net core and har file and cookie sent and received are all the same.
  • The concerning error was misleading “The server returned an invalid or unrecognized response.”, digging further we identified it was actually a HTTP 400 error underneath.

Sample log file:

Host: localhost:44341
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
upgrade-insecure-requests: 1
MS-ASPNETCORE-TOKEN: c34057dc-48b2-408b-ab2d-c4c768ebecc7
X-Forwarded-For: [::1]:54863
X-Forwarded-Proto: https
X-P2P-PeerDist: Version=1.1
X-P2P-PeerDistEx: MinContentInformation=1.0, MaxContentInformation=2.0Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44341/ 
LoggingConnectionAdapter:Debug: WriteAsync[101] 48 54 54 50 2F 31 2E 31 20 34 30 30 20 42 61 64 20 52 65 71 75 65 73 74 0D 0A 44 61 74 65 3A 20 57 65 64 2C 20 30 33 20 41 70 72 20 32 30 31 39 20 31 39 3A 35 30 3A 32 37 20 47 4D 54 0D 0A 53 65 72 76 65 72 3A 20 4B 65 73 74 72 65 6C 0D 0A 43 6F 6E 74 65 6E 74 2D 4C 65 6E 67 74 68 3A 20 30 0D 0A 0D 0A
HTTP/1.1 400 Bad Request
Date: Wed, 03 Apr 2019 19:50:27 GMT
Server: Kestrel
Content-Length: 0Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1046.4958ms 400

The actual issue:

We identified that, in development, requests are proxied to the Angular development server that gets started as a background process which is a Node.JS server which has a header limit of ~8kb. Hence, it is failing with 400 error.

Refer: https://nodejs.org/en/blog/vulnerability/november-2018-security-releases/#denial-of-service-with-lar…

Recommendation:

  • So, if you want to use AAD auth in development environment you’re going to need to slim down the cookie, likely by filtering out unneeded claims. There’re some related docs here:

         Refer: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/additional-claims?view=a…

  • Also, we can install latest Nodejs that supports increasing the header size.

         Refer: https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V10.md

Note: This issue impacts any project template that uses the following.

ASP.NET core + Angular + AAD (OAuth)

ASP.NET core + React + AAD (OAuth)

Понравилась статья? Поделить с друзьями:
  • Ошибка an unexpected error has occurred
  • Ошибка an ssl error occurred
  • Ошибка an invalid character was found
  • Ошибка an invalid argument was supplied
  • Ошибка an insert exec statement cannot be nested