简体   繁体   中英

Why does User.Identity.GetUserId<int>() in WebApi Controller return 0 everywhere except in action methods?

I'm working on a WebApi project with Asp.Net.Identity v2 (with AspNetUser modified to use int IDs). I wanted to do a bit of refactoring by creating a base class for all my web api controllers. In particular, I wanted the MyBaseController class to encapsulate the logic of getting the current user id.

Previously, each action method in each controller called User.Identity.GetUserId<int>() . it was cumbersome but worked.

Now I decided to encapsulate that call either in the base class's constructor or in its property. However, it doesn't work: The Identity object I get is empty ( IsAuthenticated = false, Name = null... ), and GetUserId<int>() always returns 0 .

Apparently it is only inside an action method that Identity is populated and GetUserId<int>() returns a correct result?

Here is basically what I get:

public class MyBaseController : ApiController
{
    public int UserId => User.Identity.GetUserId<int>(); // **this always returns 0**
    public MyBaseController() : base() 
    { var userId = User.Identity.GetUserId<int>(); // **this is always 0** }

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        var userId = User.Identity.GetUserId<int>(); // **also 0**
    }

    public IHttpActionResult Get() {
        var userId = User.Identity.GetuserId<int>(); // **the only place where it returns userId properly**
       // some code ... 
    }
}

Is there a way to grab User.Identity other than in an action method to do something with it in a base class?

The project was initially created in VS 2013 with MVC 5 / WEbapi 2, now migrated to VS2015

You cannot access User.Identity before authorization. See the APIController life cycle here or on MSDN .

The information is not yet available in the constructor or in Initialize() .

You can use a property in the base controller:

public abstract class MyBaseController : ApiController
{
    public int UserID
    {
        get { return User.Identity.GetUserId<int>(); }
    }
}

public class MyNormalController : MyBaseController
{
    public ActionResult Index()
    {
        var userId = UserID; // put in variable to avoid multiple calls
       // some code ... 
    }
}

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