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

ASP.NET Core MVC项目无法获取Windows认证用户信息问题求助

ASP.NET Core MVC项目无法获取Windows认证用户信息问题求助

各位大佬好,我最近在从零重建一个2010年的旧ASP.NET WebForms应用,用的是Visual Studio 2022 Professional的ASP.NET Core MVC(C#)项目模板。

不管跟着多少文章操作,我都没办法获取到HttpContext.User.Name的值——说白了就是想还原旧ASP.NET里通过Windows认证获取登录用户名的功能。

我试过这两种写法,结果全都是null:

HttpContext.Current.User.Identity.Name
HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value

我翻了一堆教程和文章,肯定是漏了什么关键配置,真心求各位给点思路!

下面是我的相关配置和代码:

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:38899",
      "sslPort": 0
    }
  },
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5105",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

HomeController(仅添加了获取用户的逻辑,其余为项目默认代码)

public IActionResult Index()
{
    string user = "";
    user = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
    return View();
}

Program.cs

using WebApplication1.Controllers;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddSession(options =>
{
    options.Cookie.Name = ".TestSession";
    options.IdleTimeout = TimeSpan.FromMinutes(600);
    options.Cookie.HttpOnly = true; //disallows cookie access via client side script
    options.Cookie.IsEssential = true;
});

builder.Services.AddHttpContextAccessor();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

备注:内容来源于stack exchange,提问作者Rob K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 10:34:30