Search code examples
asp.net-mvcasp.net-web-apiasp.net-identity

When changing id type from string to int, how to get id of current signed in user in Web API?


Using ASP.NET Web API along with ASP.NET Identity 1.0, you can use this extension method to retrieve the currently signed in user:

var id = Microsoft.AspNet.Identity.IdentityExtensions.GetUserId(User.Identity);

But in ASP.NET identity 2.0 alpha, you can override the type for the ID field. The example given by Microsoft shows setting this field to be an int. But this extension method seems to be hardcoded to return a string even in the alpha:

http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.111).aspx

How can you retrieve the (int) identity of the currently logged in user from within a Web API controller when using ASP.NET Identity 2.0 alpha?


Solution

  • You have to do the conversion manually yourself currently, because Claims are intrinsically strings. We could provide some sort of generic extension like User.Identity.GetUserId which tries to do a conversion from string -> T and this is something we are considering improving in future releases.