Authentication 用户成功登录后无法路由主页

Authentication 用户成功登录后无法路由主页,authentication,asp.net-core,model-view-controller,.net-core,authorization,Authentication,Asp.net Core,Model View Controller,.net Core,Authorization,由于“授权”属性,我无法在成功登录后路由回家/索引 结果: 怎么才能解决这个问题 等待你的答案 //Startup.cs public void配置服务(IServiceCollection服务) { services.AddControllersWithViews() services.Configure(选项=> { options.checkApprovered=context=>true; options.MinimumSameSitePolicy=SameSiteMode.None;

由于“授权”属性,我无法在成功登录后路由回家/索引

结果:

怎么才能解决这个问题

等待你的答案

//Startup.cs

public void配置服务(IServiceCollection服务)

{

services.AddControllersWithViews()

services.Configure(选项=>
{
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.AddDbContext(选项=>
options.UseSqlServer(
配置[“DefaultConnection”]);
服务.额外性()
//services.AddDefaultIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.AddMvc(op=>{op.EnableEndpointRouting=false;}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.configureApplicationOK(选项=>
{
options.LoginPath=$“/Account/Login”;
//options.LogoutPath=$“/Identity/Account/Logout”;
options.AccessDeniedPath=$“/Account/AccessDenied”;
});
services.AddLogging(配置=>
{
config.AddConsole();
config.AddDebug();
//等
});
services.AddTransient(
s=>s.GetService().HttpContext.User);
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
public void Configure(IApplicationBuilder应用程序、IWebHostEnvironment环境、IServiceProvider服务提供程序、iLogger工厂和loggerFactory)
{
使用(var serviceScope=app.ApplicationServices.GetService().CreateScope())
{
var context=serviceScope.ServiceProvider.GetRequiredService();
context.Database.recreated();
}
app.UseMiddleware();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseMvc();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Index}/{id?}”);
});
AddFile(“Logs/ts-{Date}.txt”);
Extensions.CreateRoles(ServiceProvider.Wait();
}
无错误返回200

由于“授权”属性,我无法在成功登录后路由回家/索引。 结果:

这是因为您没有成功地进行身份验证

要修复它,您需要添加
app.UseAuthentication()
app.UseAuthorization()之前

参考:

更新:

public async Task OnGetAsync(string returnUrl = null)
{
    if (!string.IsNullOrEmpty(ErrorMessage))
    {
        ModelState.AddModelError(string.Empty, ErrorMessage);
    }

    returnUrl = returnUrl ?? Url.Content("~/");

    // Clear the existing external cookie to ensure a clean login process
    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

    ReturnUrl = returnUrl;
}

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, set lockoutOnFailure: true
        var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");
            return LocalRedirect("/Home/Index");
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

        // If we got this far, something failed, redisplay form
        return Page();
}
公共异步任务OnGetAsync(字符串返回URL=null) { 如果(!string.IsNullOrEmpty(ErrorMessage)) { AddModelError(string.Empty,ErrorMessage); } returnUrl=returnUrl??Url.Content(“~/”); //清除现有的外部cookie以确保干净的登录过程 等待HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); ExternalLogins=(wait _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); ReturnUrl=ReturnUrl; } 公共异步任务OnPostAsync(字符串returnUrl=null) { returnUrl=returnUrl??Url.Content(“~/”); if(ModelState.IsValid) { //这不会将登录失败计入帐户锁定 //要启用密码故障触发帐户锁定,请设置lockoutOnFailure:true var result=wait _signInManager.PasswordSignInAsync(Input.Email、Input.Password、Input.RememberMe、lockoutOnFailure:true); if(result.successed) { _logger.LogInformation(“用户登录”); 返回LocalRedirect(“/Home/Index”); } if(结果要求系数) { return RedirectToPage(“./LoginWith2fa”,新的{ReturnUrl=ReturnUrl,RememberMe=Input.RememberMe}); } 如果(结果IsLockedOut) { _logger.LogWarning(“用户帐户锁定”); 返回重定向Topage(“/锁定”); } 其他的 { AddModelError(string.Empty,“登录尝试无效”); 返回页(); } } //如果我们走到这一步,有些东西失败了,重新显示形式 返回页(); }
使用app.UseAuthentication();在app.UseAuthorization()之前;但是还是一样的错误,请帮忙,你的意思是在你成功登录后,您的url始终为
https://localhost:44339/Account/Login?ReturnUrl=%2F
?您可以共享您的
帐户/Login.cshtml.cs
?我建议您可以设置断点来调试onpost方法。我将共享我的
帐户/Login.cshtml.cs
。您的
请求响应LoggingMiddleware
是什么?当您登录
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();

app.UseAuthorization();
app.UseMvc();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});
public async Task OnGetAsync(string returnUrl = null)
{
    if (!string.IsNullOrEmpty(ErrorMessage))
    {
        ModelState.AddModelError(string.Empty, ErrorMessage);
    }

    returnUrl = returnUrl ?? Url.Content("~/");

    // Clear the existing external cookie to ensure a clean login process
    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

    ReturnUrl = returnUrl;
}

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, set lockoutOnFailure: true
        var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");
            return LocalRedirect("/Home/Index");
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

        // If we got this far, something failed, redisplay form
        return Page();
}