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

.NET Core 6中WindowsPrincipal与HttpContext.User.Identity.Name返回NULL问题

问题:.NET Core 6中获取用户名返回NULL

我在.NET Core 6项目中尝试通过以下代码获取用户名,但变量x和y始终返回NULL:

var x = System.Security.Principal.WindowsPrincipal.Current.Identity.Name;
 
var y = HttpContext.User.Identity.Name;

相关文件代码

Startup.cs 文件

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using AckPackage.Data;
using AckPackage.Models;
using AckPackage.Extensions;
using System.Net;
using Microsoft.Extensions.DependencyInjection;

namespace AckPackage
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        private const string DefaultConnection = "DefaultConnection";
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AckPackage.Data.AckContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString(DefaultConnection)));

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = IISDefaults.AuthenticationScheme;
            });  //.AddNegotiate();
            services.AddAuthorization();

            //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            //.AddCookie(options =>
            //{
            //    options.LoginPath = "/Employee/Create";
            //});
            services.AddHttpContextAccessor();
            services.AddControllersWithViews();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(120);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
            services.AddRazorPages();
            //services.AddMvc().AddRazorRuntimeCompilation();
            services.BindingAppServices(Configuration);
            services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSession();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Employee}/{action=Create}/{id?}");
                endpoints.MapRazorPages();
            });
            // app.MapRazorPages();
        }
    }
}

launchsettings.json 文件

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:10222",
      "sslPort": 44314
    }
  },
  "profiles": {
    "AckPackage": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7043;http://localhost:6043",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Program.cs 文件

using AckPackage;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace TrustedSystem
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

当前仅在本地环境测试,未部署到服务器,使用.NET Core 6.0,恳请解决方法。


解决方案

针对问题从配置和代码层面逐一修复:

1. 完善Windows身份验证配置

Startup.cs中AddAuthentication缺少核心的Windows身份验证注册,修改ConfigureServices中的认证代码:

services.AddAuthentication(IISDefaults.AuthenticationScheme)
        .AddNegotiate(); // 必须启用此方法,这是.NET Core处理Windows身份验证的核心组件
services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build(); // 全局要求用户认证,避免匿名访问导致身份为空
});

2. 弃用不可靠的WindowsPrincipal.Current

System.Security.Principal.WindowsPrincipal.Current依赖传统.NET Framework线程上下文,在ASP.NET Core环境下无法稳定获取请求身份,统一使用HttpContext.User来获取当前用户信息。

3. 配置Kestrel启动的Windows身份验证支持

如果使用Project命令(Kestrel)启动项目,需要在launchsettings.json的AckPackage配置中添加环境变量:

"AckPackage": {
  "commandName": "Project",
  "dotnetRunMessages": true,
  "launchBrowser": true,
  "applicationUrl": "https://localhost:7043;http://localhost:6043",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development",
    "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Server.IISIntegration"
  }
}

该变量确保Kestrel能加载IIS集成组件以支持Windows身份验证。

4. 正确获取用户名的方式

在控制器或服务中通过HttpContext获取用户名:

// 控制器中直接使用
[Authorize]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        var userName = HttpContext.User.Identity.Name;
        return View();
    }
}

// 服务中通过依赖注入IHttpContextAccessor获取
public class UserService
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public UserService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string GetCurrentUserName()
    {
        return _httpContextAccessor.HttpContext?.User.Identity.Name;
    }
}

注意给需要获取身份的控制器或页面添加[Authorize]特性,确保请求经过认证。

5. 调整Cookie政策设置

开发环境下关闭Cookie同意检查,避免影响身份验证凭证传递:

services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => false; // 开发环境关闭同意检查
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

完成以上修改后重启项目,使用IIS Express或配置好的Kestrel启动,即可正常获取Windows用户名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 14:45:03