简体   繁体   中英

How to get Windows User Name?

I created asp.net core app with windows authentication. I see the follwoing line in _Layout.cshtml:

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

It refers to Microsoft.AspnetCore.Mvc.Razor.RazorPage.User property, which is only seem to be accessible in a Razor template. Using C#, how can I get the same value in a controller code? What namespaces should be referenced?

If your TestController Inherits from Controller . User.Identity.Name is enough. In other case it is located in

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; }
    }
}

为了获得当前用户,您可以使用此

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

It is not recommended to include the username this way as it depends on the current HTTP Context, so if you tried to unit test your controller, it will always fail as there will be no HTTP Context.

You have to abstract it in an interface and inject the implementation. ex:

 public interface ICurrentUserService
    {
        string LogingName { get; }
    }

And in your web project, you implement this interface like this

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

In your controller class, you will inject a parameter of type ICurrentUserService , and use any depdnency injection framework to inject CurrentUserService , in your test cases, you can then mock it to return a fixed username

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM