[英]Razor Page C# ASP.NET Core get Windows Username (Windows Auth)
I have a problem with Windows authentication.我有 Windows 身份验证问题。 I created a new web app with the command "dotnet new webapp --auth Windows".
我使用命令“dotnet new webapp --auth Windows”创建了一个新的 Web 应用程序。 This should have a Windows authentication which works so far with the template.
这应该有一个 Windows 身份验证,到目前为止可以与模板一起使用。 Now I would like to work with the Windows Username.
现在我想使用 Windows 用户名。 On the Razor Pages (.cshtml) I can access the username with @User.Identity.Name without any problems.
在 Razor 页面 (.cshtml) 上,我可以使用 @User.Identity.Name 访问用户名,没有任何问题。 How do I get access to the username in the (.cshtml.cs) files.
如何访问 (.cshtml.cs) 文件中的用户名。
The following attempts were made:进行了以下尝试:
Enviroment.UserName
--> works fine on local machine but not on IIS. Enviroment.UserName
--> 在本地机器上工作正常,但在 IIS 上不工作。
User.Identity.Name
- The name "User" does not exist in the current context User.Identity.Name
- 当前上下文中不存在名称“用户”
HttpContext.Current.User.Identity.Name
HttpContext.Current.User
- The name "HttpContext" does not exist in the current context HttpContext.Current.User
- 当前上下文中不存在名称“HttpContext”
System.Security.Principal.WindowsIdentity.GetCurrent().Name
My Application will run on IIS on Windows Server with Windows Authentication on.我的应用程序将在 Windows Server 上的 IIS 上运行,并启用 Windows 身份验证。
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:您需要将
IHttpContextAccessor
注入您的控制器/服务,如下所示:
Startup.cs, ConfigureServices
function: Startup.cs,
ConfigureServices
函数:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.