Alexander Schmidt
Alexander Schmidt

Reputation: 5723

Headers added by ActionFilterAttribute will not appear in ApiController

I want to be able to inject headers to WebApi controller method context using an ActionFilterAttribute:

public class HeaderInjectionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        actionContext.Request.Headers.Add("test", "test");  
        base.OnActionExecuting(actionContext);
    }
}

and using this in a controller

[HeaderInjectionFilter]
public class MotionTypeController : ApiController
{
    public bool Get()
    {
        // will return false
        return HttpContext.Current.Request.Headers.AllKeys.Contains("test");        
    }
}

As I stated out in the comment the header injected by the Filter will not be part of the HttpContext.Current. When I set a breakpoint on the last line of OnActionExecuting in the attribute I can see that it is containing the header value in the request headers.

If I change my controller to

public class MotionTypeController : ApiController
{
    public bool Get()
    {
        HttpContext.Current.Request.Headers.Add("test", "test");
        // will return true
        return HttpContext.Current.Request.Headers.AllKeys.Contains("test");        
    }
}

everything will work so I guess the actionContext of the OnActionExecuting is not the same as the HttpContext.Current of the controller.

How can I inject headers for debugging purposes?

Upvotes: 4

Views: 1520

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

As I stated out in the comment the header injected by the Filter will not be part of the HttpContext.Current

That's because you added it to the actionContext.Request.Headers collection. So make sure you are looking in the same place where you added it:

[HeaderInjectionFilter]
public class MotionTypeController : ApiController
{
    public bool Get()
    {
        return this.Request.Headers.GetValues("test").Any();
    }
}

and just forget about HttpContext.Current. Think of it as something that doesn't exist. Everytime someone uses HttpContext.Current in an ASP.NET application a little kitten dies.

Upvotes: 4

Related Questions