6
votes

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?

2
I've been converting for the time being since I haven't seen any documents or source examples of how to do this either. I'll keep an eye on this and hopefully we'll get an answer instead of having to convert to an int everywhere.Shane LeBlanc

2 Answers

6
votes

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.

6
votes

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 as : GetUserId<int>()