Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 741
BenjiFB Avatar asked Jan 13 '14 03:01

BenjiFB


People also ask

How can we get logged in user details in asp net core?

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.

How do I find HttpContext user?

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 .

What is HttpContext current user identity name?

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.


1 Answers

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.

like image 78
Hao Kung Avatar answered Oct 23 '22 22:10

Hao Kung