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

由于授权属性,成功登录后,我无法路由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

cuiqiongling8888 回答:用户成功登录后无法路由首页

  

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

那是因为您未成功进行身份验证。

要解决此问题,您需要在app.UseAuthentication();之前添加app.UseAuthorization();

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();
}
本文链接:https://www.f2er.com/3143517.html

大家都在问