synergetic synergetic - 1 month ago 37
C# Question

ASP.NET Core 1.00: 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?

Answer

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