首页 > 解决方案 > Razor Page C# ASP.NET Core get Windows Username (Windows Auth)

问题描述

I have a problem with Windows authentication. I created a new web app with the command "dotnet new webapp --auth Windows". This should have a Windows authentication which works so far with the template. Now I would like to work with the Windows Username. On the Razor Pages (.cshtml) I can access the username with @User.Identity.Name without any problems. How do I get access to the username in the (.cshtml.cs) files.

The following attempts were made:

Enviroment.UserName --> works fine on local machine but not on IIS.

User.Identity.Name - The name "User" does not exist in the current context

HttpContext.Current.User.Identity.Name

HttpContext.Current.User - The name "HttpContext" does not exist in the current context

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

My Application will run on IIS on Windows Server with Windows Authentication on.

I hope someone can help me. Thank you in advance and have a nice day

标签: c#asp.netrazorwindows-authenticationrazor-pages

解决方案


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

推荐阅读