Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi ActionFilterAttribute, HttpActionContext access user name (IPrincipal) [duplicate]

I need to access the currently logged in user in my action filter. The identity is set by a DelegatingHandler further up the chain of execution.

I can access the current IPrincipal using HttpContext.Current.User. So far I avoided using HttpContext.Current as it appeared to me to be bad style. First of all your code will only work if hosted in IIS and secondly it includes a reference to System.Web which I guess doesn't hurt but I'd prefer to stick with System.Net.Http if possible. It just feels wrong to rely on good old "HttpContext".

Is there any other way to access the user's identity within an ActionFilter? Or is it okay to use HttpContext if you don't plan on running a self hosted application?

like image 215
lapsus Avatar asked Mar 11 '13 09:03

lapsus


1 Answers

I overlooked the obvious. I didn't realize there was a Controller property inside the ControllerContext.

var username = ((ApiController)context.ControllerContext.Controller).User.Identity.Name;
like image 177
lapsus Avatar answered Oct 18 '22 17:10

lapsus