You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 2.0 Cookie认证:判断用户登录状态并控制登录页显示

在ASP.NET Core 2.0 Cookie认证中判断用户登录状态

嘿,这问题我熟!要实现「未登录显示登录页、已登录直接跳转到首页」的逻辑,咱们分两步来搞定:

1. 先确保Cookie认证的基础配置正确

首先得在Startup.cs里把Cookie认证配置好,这是一切的前提:

在ConfigureServices方法中添加认证服务

using Microsoft.AspNetCore.Authentication.Cookies;

public void ConfigureServices(IServiceCollection services)
{
    // 其他服务配置...
    
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            // 指定未认证用户的跳转路径(默认就是/Account/Login,这里明确写出来更清晰)
            options.LoginPath = "/Account/Login";
            // 可选:指定登出路径
            options.LogoutPath = "/Account/Logout";
        });
    
    services.AddMvc();
}

在Configure方法中启用认证中间件

注意要把UseAuthentication放在UseMvc之前,不然认证逻辑不会生效:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // 其他中间件配置(比如UseStaticFiles、UseDeveloperExceptionPage等)...
    
    // 启用认证中间件
    app.UseAuthentication();
    
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

2. 修改AccountController的Login方法

接下来就是核心逻辑:在Login的GET请求方法里,判断用户是否已登录,如果是就直接重定向到首页。

修改后的代码如下:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

public class AccountController : CommonController
{
    // 构造函数保持你的原有代码
    public AccountController(IOptions<ConnectionSetting> connString) : base(connString) { }

    public IActionResult Index()
    {
        return RedirectToAction("Index", "Home");
    }

    [HttpGet]
    [AllowAnonymous] // 必须加这个,允许未认证用户访问登录页
    public IActionResult Login()
    {
        // 检查当前用户是否已通过认证
        if (User.Identity.IsAuthenticated)
        {
            // 已登录,直接跳转到首页
            return RedirectToAction("Index", "Home");
        }
        // 未登录,返回登录视图
        return View();
    }

    // 补充完整的POST登录方法示例
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        if (ModelState.IsValid)
        {
            // 替换成你的用户验证逻辑(比如从数据库校验用户名密码)
            bool isValidUser = VerifyUserCredentials(model.Username, model.Password);

            if (isValidUser)
            {
                // 创建用户身份声明
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.Username)
                };
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                
                // 生成认证Cookie,完成登录
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

                // 登录成功后跳转到首页
                return RedirectToAction("Index", "Home");
            }

            ModelState.AddModelError("", "用户名或密码错误");
        }

        // 验证失败,返回登录页
        return View(model);
    }

    // 辅助方法:模拟用户验证(替换成你的实际逻辑)
    private bool VerifyUserCredentials(string username, string password)
    {
        return username == "admin" && password == "password";
    }
}

关键说明

  • User.Identity.IsAuthenticated:这是ASP.NET Core内置的属性,用来判断当前请求的用户是否持有有效的认证Cookie。
  • [AllowAnonymous]:必须给Login方法加上这个特性,否则未登录用户会被自动重定向到登录页,陷入死循环。

这样配置后,当用户未登录时访问/Account/Login会显示登录页;如果已经登录(持有有效认证Cookie),访问该路径会直接跳转到Home/Index,完美实现你的需求!

内容的提问来源于stack exchange,提问作者Anish Bhattarai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:02:14