【问题标题】:Razor Page C# ASP.NET Core get Windows Username (Windows Auth)Razor Page C# ASP.NET Core 获取 Windows 用户名(Windows Auth)
【发布时间】:2023-04-10 07:50:02
【问题描述】:

我遇到了 Windows 身份验证问题。我使用命令“dotnet new webapp --auth Windows”创建了一个新的网络应用程序。这应该有一个到目前为止与模板一起工作的 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 上运行。

我希望有人可以帮助我。提前感谢您,祝您有愉快的一天

【问题讨论】:

    标签: c# asp.net razor windows-authentication razor-pages


    【解决方案1】:

    您需要将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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2022-01-26
      相关资源
      最近更新 更多