WebApi ActionFilterAttribute, HttpActionContext access user name (IPrincipal)

lapsus picture lapsus · Mar 11, 2013 · Viewed 9.1k times · Source

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?

Answer

lapsus picture lapsus · Mar 11, 2013

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;