Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current user, within an ApiController action, without passing the userID as a parameter

How do we get the current user, within an secure ApiController action, without passing the userName or userId as a parameter?

We assume that this is available, because we are within a secure action. Being in a secure action means that the user has already authenticated and the request has her bearer token. Given that WebApi has authorized the user, there may be a built in way to access the userId, without having to pass it as an action parameter.

like image 275
Shaun Luttin Avatar asked Feb 07 '14 00:02

Shaun Luttin


People also ask

How do I return a view in ApiController?

So, if you want to return a View you need to use the simple ol' Controller . The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage ( View ) for a user you don't use the Web API.

Is ApiController deprecated?

There is indeed no particular ApiController class anymore since MVC and WebAPI have been merged in ASP.NET Core. However, the Controller class of MVC brings in a bunch of features you probably won't need when developing just a Web API, such as a views and model binding.


2 Answers

In WebApi 2 you can use RequestContext.Principal from within a method on ApiController

like image 152
Darrel Miller Avatar answered Oct 01 '22 13:10

Darrel Miller


You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id; id = User.Identity.GetUserId(); id = RequestContext.Principal.Identity.GetUserId(); 
like image 27
Patrick Avatar answered Oct 01 '22 13:10

Patrick