User.Identity.Name - which assembly reference brin

2019-05-10 19:46发布

问题:

I can't find out which reference assembly the User.Identity.Name comes from. How do I find that out? I need to add it to a class library rather than the default MVC 5 app I have made so that I can have access to it?

http://msdn.microsoft.com/en-us/library/system.web.httpcontext.user(v=vs.110).aspx

C# Class Library / AUser.cs

public class AUser
{
    public string Username
    {
        get
        {
            return User.Identity.Name // doesn't notice User
        }
    }
}

回答1:

Appears to be in the System.Web namespace.

http://msdn.microsoft.com/en-us/library/system.web.httpcontext.user(v=vs.110).aspx

EDIT

Based on your additional code, you have to include the fully qualified name - such as:

HttpContext.Current.User.Identity.Name

When you are outside of a controller (or in another class). Be aware that if this outside of MVC class is used in anything without an HttpContext, it will fail (with a NullReferenceException). To ensure we don't have any of those, we typically either pass the HttpContext or the portions we need (Username, Url, etc) as function parameters.