c# - 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
解决方案
您需要将其注入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;
}
推荐阅读
- ios - Flutter:iphone应用程序没有在模拟器中运行
- google-cloud-platform - 如何使 http 云功能只能从云端点访问
- c# - 在 DST 时间更改的情况下,将时间范围和间隔拆分为多个时间范围
- spring-cloud-task - 使用 DeployerPartitionHandler 为通过 spring 云任务运行的 spring 批处理在 launchWorker 中获取空指针异常
- maven - 通过 Maven 生成 EJB 2 STUBS & TIES
- c++ - GCC 和 Clang 之间关于重载和模板化流运算符的重载解析的区别<<
- python - 在第一个元素后使用 Selenium 返回空值
- reactjs - 如何在“上下文”的 .map() 方法中迭代状态数组?
- reactjs - TypeError:使用 React、Storybook 和 Storyshots 插件进行快照测试时,提供的值不是“元素”类型
- wicket - 我如何为“表单”检票口中的输入提交添加新属性