When changing the id type from a string to int, how to get the identifier of the current signed-up user in the web API?

Using the ASP.NET Web API with ASP.NET Identity 1.0, you can use this extension method to retrieve the current 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 identifier field . The example provided by Microsoft shows that this field is int. But this extension method seems hard-coded to return a string even in alpha:

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

How can you get the identifier (int) of the current user as part of the web API controller when using ASP.NET Identity 2.0 alpha?

+6
source share
2 answers

You must manually perform the conversion manually, because the claims are internal strings. We could provide some kind of general extension, for example User.Identity.GetUserId, which is trying to convert from a string → T, and this is what we are looking at in future versions.

+6
source

I ended up using:

 public static class IdentityExtensions { public static T GetUserId<T>(this IIdentity identity) where T : IConvertible { return (T)Convert.ChangeType(identity.GetUserId(), typeof(T)); } } 

and calling it like: GetUserId<int>()

+6
source

All Articles