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
You need to inject the IHttpContextAccessor
into your controllers/services, like this:
Startup.cs, ConfigureServices
function:
services.AddHttpContextAccessor();
In your controller/service:
private readonly IHttpContextAccessor _httpContextAccessor;
public ProjectionSqlService(IHttpContextAccessor httpContextAccessor)
{
_configuration = configuration;
_httpContextAccessor = httpContextAccessor;
var username = _httpContextAccessor.HttpContext.User.Identity.Name;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.