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

ASP.NET Core中获取当前UserId始终为空的问题及解决方法

ASP.NET Core Identity中CurrentUserService无法获取用户ID的问题及解决

问题背景

在ASP.NET Core项目中使用Identity框架时,已在Startup中注册以下服务:

services.AddSingleton<ICurrentUserService, CurrentUserService>();
services.AddHttpContextAccessor();

同时实现了AccountController完成登录登出功能:

[ApiController]
[Route("api/[controller]")]
public class AccountController : Controller
{
    private readonly IApplicationUserManager _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    public AccountController
    (IApplicationUserManager userManager,
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        //_roleManager = roleManager;
        _signInManager = signInManager;
    }

    [HttpPost("Login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        try
        {
            await _signInManager.SignOutAsync();

            var result = await _signInManager.PasswordSignInAsync(model.email, model.password, true, false);

            if (result.Succeeded)
            {
                return Json(new { success = true});
            }

            var message = string.Join("; ", ModelState.Values
                .SelectMany(x => x.Errors)
                .Select(x => x.ErrorMessage));

            return Json(new
            {
                success = false,
                Message = message
            });

        }
        catch (Exception e)
        {
            return Json(new
            {
                success = false,
                Message = e.Message
            });
        }

    }

    [HttpPost("logout")]
    public IActionResult LogOut()
    {
        try
        {
            _signInManager.SignOutAsync();
            return Ok(new { success = true });
        }
        catch (Exception e)
        {
            return Ok(new { success = false, Message = e.Message });
        }

    }
}

另外实现了CurrentUserService用于获取当前用户信息:

public class CurrentUserService : ICurrentUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;

public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

public Guid? UserId => Guid.Parse(_httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier) ?? string.Empty);

public string FullName => _httpContextAccessor.HttpContext?.User?.FindFirstValue("FullName") != null
                ? _httpContextAccessor.HttpContext?.User?.FindFirstValue("FullName")
                : _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);

public string Avatar => _httpContextAccessor.HttpContext?.User?.FindFirstValue("Avatar") != null
    ? _httpContextAccessor.HttpContext?.User?.FindFirstValue("Avatar")
    : "/Themes/img/no_avatar.png";
}

遇到的问题:_httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier)始终返回null。

解决方法

在Startup的中间件配置中添加以下代码后,问题得到解决:

app.UseAuthorization();
app.UseAuthentication();

注:正确的中间件顺序应为先调用app.UseAuthentication()再调用app.UseAuthorization(),这样认证逻辑会先执行,确保用户身份信息被正确解析后再进行授权检查。

内容的提问来源于stack exchange,提问作者ar.gorgin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:55:32