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

ASP.NET Core使用Cookie和Claims调用HttpContext.SignInAsync失败

ASP.NET Core Cookie身份验证SignInAsync报错解决方案

核心错误原因

  • HttpContext.SignInAsync 是异步方法,你当前以同步方式直接调用未加await,请求上下文会在身份校验写入Cookie的操作完成前就被释放,导致调用异常
  • 你注册的Cookie认证方案名为CookieAuth,调用SignInAsync时未显式指定方案名,可能出现方案不匹配问题

修复步骤

  1. 将Login方法改为异步签名,返回Task<IActionResult>,调用SignInAsync时添加await关键字,同时显式传入你注册的认证方案名CookieAuth
  2. 补充空值校验逻辑,避免用户不存在时抛出空引用异常

修复后Login方法代码示例

// 引入必备命名空间
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;

public async Task<IActionResult> Login(LoginModel lm)
{
    using (var ctx = new GroupHomeContext())
    {
        try 
        {
            var user = ctx.Logins.SingleOrDefault(er => er.UserName == lm.UserName);
            // 补充用户为空的校验逻辑
            if (user == null)
            {
                return RedirectToAction("/Account/SignIn");
            }
            if (Decrypt(user.Password) == lm.Password)
            {
                var employee = ctx.Employees.SingleOrDefault(em => em.EmployeeId == user.EmployeeId);
                var employeeRole = ctx.EmployeeToRoles.SingleOrDefault(er => er.EmployeeId == employee.EmployeeId);
                var Role = ctx.Roles.SingleOrDefault(rl => rl.RoleId == employeeRole.RoleId);

                var GroupHomeClaims = new List<Claim>() 
                { 
                    new Claim(ClaimTypes.NameIdentifier, employee.EmployeeId.ToString()), 
                    new Claim(ClaimTypes.Email, employee.Email), 
                    new Claim(ClaimTypes.Role, employeeRole.RoleId.ToString()) 
                };
                var GroupHomeIdentity = new ClaimsIdentity(GroupHomeClaims, "Group Home Identity");
                var userPrincipal = new ClaimsPrincipal(new[] { GroupHomeIdentity });

                if (userPrincipal != null)
                {
                    // 增加await关键字+显式指定注册的认证方案名
                    await HttpContext.SignInAsync("CookieAuth", userPrincipal);
                    return RedirectToAction("/Dashboard/Employees");
                }
                return RedirectToAction("/Account/SignIn");
            }
            return RedirectToAction("/Account/SignIn");
        }
        catch (Exception ex)
        {
            return RedirectToAction("/Account/SignIn");
        }
    }
}

额外检查项

你当前Startup.cs里的中间件顺序是正确的,UseAuthentication放在UseAuthorization之前符合要求,无需调整。只需要确认项目已经安装了Microsoft.AspNetCore.Authentication.Cookies NuGet包即可。

内容的提问来源于stack exchange,提问作者Carlos Andrés Montoya Cardona

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:45:09