Search code examples
c#asp.net-mvcasp.net-identity-3

Can't retrieve UserId from Microsoft.AspNet.Identity


I have created a new class that I want to manage a few things, one of which is to get the User Id Microsoft.AspNet.Identity. I get this error message

CS0103 The name 'User' does not exist in the current context

And this is my code:

using Microsoft.AspNet.Identity;

public string UserId
{
    get
    {
        return User.Identity.GetUserId();
    }
}

enter image description here

I was expecting intellisense to pick up the Microsoft.AspNet.Identity GetUserId method, but I get the error below.

What am I doing wrong and why can't it pick up the UserId from Microsoft.AspNet.Identity.


Solution

  • You should use HttpContext.Current.Userlike this:

    public string UserId
    {
        get { return HttpContext.Current.User.Identity.GetUserId(); }
    }
    

    Because based on MSDN:

    if you want to use the members of IPrincipal from an ASP.NET code-behind module, you must include a reference to the System.Web namespace in the module and a fully qualified reference to both the currently active request/response context and the class in System.Web that you want to use. For example, in a code-behind page you must specify the fully qualified name HttpContext.Current.User.Identity.Name.

    As an another note, you can also use the C# 6+ new feature called expression-bodied property like this:

    public string UserId => HttpContext.Current.User.Identity.GetUserId();