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

Posted

技术标签:

【中文标题】用户成功登录后无法路由主页【英文标题】:Cant route home page after user successfully login 【发布时间】:2020-03-04 05:42:42 【问题描述】:

由于授权属性,我在成功登录后无法路由 Home/Index。

结果:https://localhost:44339/Account/Login?ReturnUrl=%2F

我该如何解决这个问题

等待你的回答

//Startup.cs

public void ConfigureServices(IServiceCollection 服务)

services.AddControllersWithViews();

        services.Configure<CookiePolicyOptions>(options =>
        
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        );

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration["DefaultConnection"]));

        services.AddIdentity<User, IdentityRole>()
            // services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc(op=>  op.EnableEndpointRouting = false;).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);


        services.ConfigureApplicationCookie(options =>
        
            options.LoginPath = $"/Account/Login";
           // options.LogoutPath = $"/Identity/Account/Logout";
            options.AccessDeniedPath = $"/Account/AccessDenied";
        );
        services.AddLogging(config =>
        
            config.AddConsole();
            config.AddDebug();
            //etc
        );
        services.AddTransient<ClaimsPrincipal>(
             s => s.GetService<IHttpContextAccessor>().HttpContext.User);


    

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider ServiceProvider ,ILoggerFactory loggerFactory)
    
        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.EnsureCreated();
        
        app.UseMiddleware<RequestResponseLoggingMiddleware>();

        if (env.IsDevelopment())
        
            app.UseDeveloperExceptionPage();
        
        else
        
            app.UseExceptionHandler("/Home/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.UseRouting();
        app.UseAuthorization();
        app.UseMvc();
        app.UseEndpoints(endpoints =>
        
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "controller=Home/action=Index/id?");
        );
        loggerFactory.AddFile("Logs/ts-Date.txt");

        Extensions.CreateRoles(ServiceProvider).Wait();
    

没有错误返回200

【问题讨论】:

【参考方案1】:

由于授权属性,我在成功登录后无法路由 Home/Index。 结果:https://localhost:44339/Account/Login?ReturnUrl=%2F

那是因为你没有成功认证。

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

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();
);

参考:Configure Identity services

更新:

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();

【讨论】:

使用 app.UseAuthentication();在 app.UseAuthorization() 之前;但仍然是同样的错误请帮助 那么,你的意思是你登录成功后,你的url总是https://localhost:44339/Account/Login?ReturnUrl=%2F?能分享一下你的Account/Login.cshtml.cs吗?我建议你可以设置断点来调试你的onpost方法。我会分享我的Account/Login.cshtml.cs。你的RequestResponseLoggingMiddleware 是什么?你登录的时候有用吗?

以上是关于用户成功登录后无法路由主页的主要内容,如果未能解决你的问题,请参考以下文章

登录成功后重定向express js路由

MVC 区域路由登录后

迁移到 ASP.NET 3.1 - 从登录控制器路由到 Razor 页面主页索引页面不再工作

用户登录后路由到用户帐户

成功登录后推送(重定向)到路由

登录后无法重定向