Razor页面C#ASP.NET Core获取Windows用户名Windows Auth

问题描述

我对Windows身份验证有问题。我使用命令“ dotnet new webapp --auth Windows”创建了一个新的Web应用程序。到目前为止,该模板应具有Windows身份验证,该身份验证可与模板一起使用。现在,我想使用Windows用户名。在Razor页面(.cshtml)上,我可以使用@ User.Identity.Name访问用户名,而不会出现任何问题。如何访问(.cshtml.cs)文件中的用户名

进行了以下尝试:

Enviroment.UserName->在本地计算机上运行良好,但在IIS上运行不正常。

User.Identity.Name-名称用户”在当前上下文中不存在

HttpContext.Current.User.Identity.Name

HttpContext.Current.User-当前上下文中不存在名称“ HttpContext”

System.Security.Principal.WindowsIdentity.GetCurrent().Name

我的应用程序将在启用Windows身份验证的Windows Server上的IIS上运行。

我希望有人能帮助我。预先谢谢您,祝您愉快!

解决方法

您需要将IHttpContextAccessor注入到控制器/服务中,如下所示:

Startup.cs,ConfigureServices函数:

services.AddHttpContextAccessor();

在您的控制器/服务中:

private readonly IHttpContextAccessor _httpContextAccessor;

public ProjectionSqlService(IHttpContextAccessor httpContextAccessor)
{
    _configuration = configuration;
    _httpContextAccessor = httpContextAccessor;

    var username = _httpContextAccessor.HttpContext.User.Identity.Name;
}