首页 > 解决方案 > 尝试使用带有 ASP.NET 身份的 cookie 身份验证登录时获取 HTTP 500

问题描述

ASP.NET 核心 2.2

这个问题我纠结了很久...

每当我尝试通过 HttpContext 进行与登录或注销相关的任何操作时,都会收到 HTTP 500 错误。

我已经搭建了身份并完成了我需要的更改,因此我或多或少地一对一地使用了微软的 GitHub 代码。


我正在执行的操作已完成(登录/注销、更改密码)RedirectToPage()调用仅返回 HTTP 500 错误。

我怀疑它必须重新加载太快而不等待 HttpContext 登录或验证?

我已经设法使登录工作而不是RedirectToPage()使用Response.Redirect(returnUrl)

这是我的Startup.cs

   public void ConfigureServices(IServiceCollection services)
    {
        // Add httpcontext service
        services.AddHttpContextAccessor();
        // Services identity depends on
        services.AddScoped<IIdentityRepository, IdentityRepository>();
        //services.AddOptions().AddLogging();

        // Services used by identity
        services.AddScoped<IUserStore, UserStore>();
        services.AddScoped<IUserValidator, UserValidator>();
        services.AddScoped<IPasswordValidator, PasswordValidator>();
        services.AddScoped<IPasswordHasher, PasswordHasher>();
        services.AddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
        // No interface for the error describer so we can add errors without rev'ing the interface
        services.AddTransient<IdentityErrorDescriber>();
        services.AddScoped<UserManager>();
        services.AddScoped<SignInManager>();

        // Identity cookie paths
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.AccessDeniedPath = "/Identity/Account/AccessDenied";
                o.LoginPath = "/Identity/Account/Login";
                o.Cookie.HttpOnly = true;
            });


        // Require authorization on every page by default
        // Allow areas and add an area to path
        services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;
                options.Conventions.AddAreaPageRoute("App", "/summary", "");
            });

        services.AddRouting(options => options.LowercaseUrls = true);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseMvc();
    }

更改密码的剃刀页面示例:(正确输入正确的旧密码和新密码后,我收到 HTTP 500 错误)

public async Task<IActionResult> OnPostAsync () {
if (!ModelState.IsValid) {
    return Page ();
}

var user = await _userManager.GetUserAsync (User);
if (user == null) {
    return NotFound ($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}

var changePasswordResult = await _userManager.ChangePasswordAsync (user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded) {
    foreach (var error in changePasswordResult.Errors) {
        ModelState.AddModelError (string.Empty, error.Description);
    }
    return Page ();
}

await _signInManager.RefreshSignInAsync (user);
//_logger.LogInformation("User changed their password successfully.");
StatusMessage = "Your password has been changed.";

return RedirectToPage(); // THIS PROBABLY CAUSING THE HTTP 500

}

标签: asp.netasp.net-coreasp.net-identitycookie-authentication

解决方案


Thanks to @poke I got the answer.

The exceptions not shown when getting a 500 error in the browser will be displayed in Visual Studios Output window when you Debug your app.

My specific problem was in a Dispose method throwing not yet implemented in the User Store class.


推荐阅读