如何获取Windows用户名?

How to get Windows User Name?

我创建了 asp.net 具有 windows 身份验证的核心应用程序。我在 _Layout.cshtml 中看到以下行:

<p class="nav navbar-text navbar-right">Hello, @User.Identity.Name!</p>

它指的是 Microsoft.AspnetCore.Mvc.Razor.RazorPage.User 属性,它似乎只能在 Razor 模板中访问。使用 C#,如何在控制器代码中获得相同的值?应该引用哪些命名空间?

要获取当前用户,您可以使用此

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

如果您的 TestController 继承自 ControllerUser.Identity.Name 就够了。在其他情况下,它位于

namespace System.Security.Principal
{
    //
    // Summary:
    //     Defines the basic functionality of an identity object.
    public interface IIdentity
    {
        //
        // Summary:
        //     Gets the type of authentication used.
        //
        // Returns:
        //     The type of authentication used to identify the user.
        string AuthenticationType { get; }
        //
        // Summary:
        //     Gets a value that indicates whether the user has been authenticated.
        //
        // Returns:
        //     true if the user was authenticated; otherwise, false.
        bool IsAuthenticated { get; }
        //
        // Summary:
        //     Gets the name of the current user.
        //
        // Returns:
        //     The name of the user on whose behalf the code is running.
        string Name { get; }
    }
}

不建议以这种方式包含用户名,因为它取决于当前的 HTTP 上下文,因此如果您尝试对控制器进行单元测试,它将始终失败,因为没有 HTTP 上下文。

你必须在接口中抽象它并注入实现。 例如:

 public interface ICurrentUserService
    {
        string LogingName { get; }
    }

并且在你的 web 项目中,你实现这个接口是这样的

public class CurrentUserService : ICurrentUserService
{
  public LoginName
   {
     get
       {
          return HttpContext.Current.User.Identity.Name;
       }
    }
 }

在你的控制器class中,你将注入一个类型为ICurrentUserService的参数,并使用任何依赖注入框架来注入CurrentUserService,然后在你的测试用例中,你可以模拟它到return一个固定的用户名