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?
try this System.Web.HttpContext.Current.User.Identity.Name ? It should work. See the samples in asp.net github.com/aspnet/Identity/blob/…. Just make sure user is logged in.
HttpContext. User); Then in your DI object that needs the user you just inject IPrincipal to get the current user. The most important thing here is if you're doing unit tests you don't need to send in an HttpContext , but only need to mock something that represents IPrincipal which can just be ClaimsPrincipal .
It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With