首页 > 解决方案 > 当 Web 应用程序以管理员身份运行时,如何在 ASP.NET Core 2.2 中获取当前 Windows 用户名?

问题描述

我们有一个 ASP.NET Core 2.2 Web 应用程序,托管在 IIS 上并在MyComputer\MyAdminUser Windows 用户(具有管理员权限)下运行。我需要获取正在使用我们的应用程序 f.ex 的当前 Windows 用户的名称。MyComputer\MyClientUser。所有客户端用户都是本地用户(MyComputer\ ...)。我该怎么做?

我尝试使用不同的方法,但没有人给我带来预期的结果(MyClientUser):

1. HttpContext.Current.Request.LogonUserIdentity;

“HttpContext”不包含“ Current”的定义,并且找不到接受“HttpContext”类型的第一个参数的可访问扩展方法“Current”...

2. Request.LogonUserIdentity;

同样的问题LogonUserIdentity

3. Request.ServerVariables["LOGON_USER"];

同样的问题ServerVariables

4. Request.Headers

此列表不包含有关当前 Windows 用户的任何信息

5. Environment.UserName

结果是“我的管理员用户”

6. WindowsIdentity.GetCurrent().Name

结果是“MyComputer\MyAdminUser”

7. ManagementObjectCollection collection = 
      new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
      .Get();
   collection?.Cast<ManagementBaseObject>()?.First()?.Properties?["UserName"]?.Value

对于 Visual Studio 结果是正确的(当前 Windows 用户),但在 IIS 上Properties?["UserName"]?.Value为 null 或空 ( Properties?["UserName"]?.Name= "UserName")

我做错了什么,我怎样才能得到预期的名字?

标签: c#iisasp.net-core-2.2windows-users

解决方案


推荐阅读