i'm using web Api in my MVC Application and i wanna get user Identity in my api with following code :
User.Identity.Name
but it doesn't work although ,it works well in other Places like controllers!
Is there any solution to access the User.Identity.Name from the Web API?
This is a common confusion. Being authenticated in MVC does nothing for your authenticated state in Web Api. Web Api is REST-compliant, which among other things, means its stateless -- no sessions.
When you authenticate on the MVC side, a cookie is added to the user's browser with an auth token, corresponding an active authentication in the application's session state (I'm not talking about Session here, as auth doesn't use that, but it's still using sessions). Then, on each subsequent request, the browser passes this cookie back to the server which verifies the auth token and restores the user's state of being "logged in".
In Web Api, none of this happens. Each request to a Web Api must contain all the information necessary to process that request. There is no knowledge of what came before. So, if you need to authorize a Web Api request, you must pass an auth token along with the request, usually in the request headers. Otherwise, you are not authenticated and User.Indentity.Name will be null, because you're anonymous.
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