首页 > 解决方案 > 登录后也能进入登录页面

问题描述

我正在使用启用了个人用户身份验证的默认模型-视图-控制器模板。问题是当我登录后,我仍然可以进入登录页面。如何预防?

标签: asp.net-core

解决方案


您可以自定义中间件以在用户登录并访问登录页面时重定向。

重定向中间件.cs

public class RedirectMiddleware
{
    private readonly RequestDelegate _next;

    public RedirectMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if(context.Request.Path == "/Identity/Account/Login")
        {
            if (context.User.Identity.IsAuthenticated)
            {
                context.Response.Redirect("/Home/Index");
            }
        }
        await _next.Invoke(context);
    }
}

启动.cs

app.UseMiddleware<RedirectMiddleware>();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

或者

直接在 Login OnGetAsync Handler 中做重定向:

public async Task OnGetAsync(string returnUrl = null)
    {
        if (!string.IsNullOrEmpty(ErrorMessage))
        {
            ModelState.AddModelError(string.Empty, ErrorMessage);
        }
        if (User.Identity.IsAuthenticated)
        {
            Response.Redirect("/Home/Index");
        }
        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;
    }

推荐阅读