[英]Razor Page C# ASP.NET Core get Windows Username (Windows Auth)
我有 Windows 身份驗證問題。 我使用命令“dotnet new webapp --auth Windows”創建了一個新的 Web 應用程序。 這應該有一個 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 Server 上的 IIS 上運行,並啟用 Windows 身份驗證。
我希望有一個人可以幫助我。 提前謝謝你,祝你有美好的一天
您需要將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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.