Headers added by ActionFilterAttribute will not display in ApiController

I want to be able to enter headers in the context of a WebApi controller method with ActionFilterAttribute:

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

and using this in the controller

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

As I said in the comment, the title entered by the filter will not be part HttpContext.Current. When I set a breakpoint on the last line OnActionExecutingin the attribute, I see that it contains 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 think that actionContextto OnActionExecutingnot coincide with the HttpContext.Currentcontroller.

How can I insert headers for debugging purposes?

+4
source share
1

, , , HttpContext.Current

, actionContext.Request.Headers. , , :

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

HttpContext.Current. -, . , - HttpContext.Current ASP.NET, .

+4

Source: https://habr.com/ru/post/1622714/


All Articles