如何在.NET 6 ASP.NET Core Web API中获取LogonUserIdentity用户信息?
解决.NET 6 ASP.NET Core Web API获取Domain\Username的问题
问题原因
你当前的代码未启用Windows身份验证,导致HttpContext.User.Identity无法获取到用户身份信息,返回null。.NET Framework中的LogonUserIdentity依赖Windows身份验证机制,在.NET Core中需要显式配置对应的身份验证服务。
解决方案步骤
- 添加Windows身份验证服务
在builder.Services.AddControllers();之后,添加Negotiate身份验证服务(.NET Core中用于Windows身份验证的标准方案,支持Kerberos和NTLM):
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) .AddNegotiate();
如果项目未安装对应依赖,需添加Microsoft.AspNetCore.Authentication.Negotiate NuGet包。
- 调整中间件顺序
中间件执行顺序直接影响功能生效,需确保:
UseCors放置在UseAuthentication之前UseAuthentication必须在MapControllers之前
修改后的完整program.cs代码如下:
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // 配置Windows身份验证服务 builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) .AddNegotiate(); builder.Services.AddCors(options => { options.AddPolicy(name: "corsPolicy", policy => { policy.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); // 启用CORS app.UseCors("corsPolicy"); // 启用身份验证 app.UseAuthentication(); // 启用授权(按需添加) app.UseAuthorization(); app.MapControllers(); app.Run();
- 获取用户名
在接口中使用以下代码即可获取domain\username格式的用户名:
var username = HttpContext.User.Identity?.Name;
部署注意事项
- IIS部署:在IIS站点的身份验证设置中,启用Windows身份验证,禁用匿名身份验证。
- Kestrel部署:Kestrel默认支持Windows身份验证,无需额外配置,但需确保运行程序的账户具备对应权限。
内容的提问来源于stack exchange,提问作者sdman02
相关产品推荐
相关产品推荐

