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

1

12

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?

Assertive answered 11/3, 2013 at 9:20 Comment(1)
Damn.. I really really searched thoroughly before posting the question. 5min later I have two working answers :(Assertive
A
18

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;
Assertive answered 11/3, 2013 at 9:26 Comment(1)
in Web API v2 actionContext.RequestContext.Principal will do the trick.League

© 2022 - 2024 — McMap. All rights reserved.