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.
相关产品推荐
相关产品推荐

