Reputation: 458
I have a Web API service that passes in an ApiKey with the request header. A custom action filter (AuthenticationRequiredAttribute) derived from ActionFilterAttribute overrides the OnActionExecuting method and does a DB call to get the ClientId associated with a valid ApiKey. I can assign the ClientID as a property via HttpActionContext.Request.Properties.Add ("clientID", clientID)
, but then I cannot access the associated actionContext object in the controller action method, so it is of no value.
Surely this is a common situation, but I cannot find an good example dealing with it. How do I get the HttpActionContext instance into the controller class?
Here is the filter:
public override void OnActionExecuting(HttpActionContext actionContext)
Within this, I get the ClientID, but I don't see how to pass it to the method below:
Here is the Controller's method:
[Route("v1/stock/{SecurityId}/text")]
public HttpResponseMessage GetSummaryTextV1(string SecurityId, string topic = "")
The HttpActionContext is not available within. I need ClientID in here, but cannot get it.
Is there a way that I can pass the current actionContext into the Controller constructor?
At a loss, hard-wiring the clientId for now, so I can proceed.
Upvotes: 1
Views: 1621
Reputation: 458
I found an easy solution to this problem. Rather than use a custom 'AuthenticationRequired' attribute derived from the ActionFilterAttribute class and specified in global.asax:
GlobalConfiguration.Configuration.Filters.Add(new AuthenticationRequiredAttribute());
public class AuthenticationRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
/* My authentication and lookup logic here */
}
}
I simply put the logic in a new Controller constructor with fields whose values are filled on successful authentication. It is simple and straight-forward. No HttpActionContext.Request.Properties.Add gobbledygook, no resurrecting the session object, just fields and a constructor. Duh. That being said, I do appreciate the two suggestions I received; I just was not able to implement them.
Upvotes: 0
Reputation: 3347
Use Request.Properties
to access the properties.
EDIT:
You can set the CliendID in the properties like you have in your question
HttpActionContext.Request.Properties.Add ("clientID", clientID)
and access the properties in your controller using Request.Properties
Upvotes: 0
Reputation: 11954
See: http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/
I have implemented this approach. Once the caller is authenticated, I store their client id in a custom IIdentity
that I then use inside the controllers.
Upvotes: 0