1

Im trying to add a header attribute to a controller, but the Response is null with the HttpActionContext property. Am I doing something wrong?

Controller.cs

[ExceptionHandling, ApiValidation, HttpHeader("X-Robots-Tag", "noindex, nofollow")]
    public abstract class BaseApiController : System.Web.Http.ApiController
    {

HttpHeaderFilter.cs

   public class HttpHeaderAttribute : System.Web.Http.Filters.FilterAttribute 
{
    public string Name { get; set; }
    public string Value { get; set; }

    public HttpHeaderAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }
}

public class HttpHeaderFilter : System.Web.Http.Filters.IActionFilter
{
    private readonly string _name;
    private readonly string _value;

    public HttpHeaderFilter(string name, string value)
    {
        _name = name;
        _value = value;
    }

    public bool AllowMultiple
    {
        get { return true; }
    }

    public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        actionContext.Response.Headers.Add(_name, _value);

        return continuation();
    }
}

Global.asax

kernel.BindHttpFilter<HttpHeaderFilter>(System.Web.Http.Filters.FilterScope.Controller)
                       .WhenControllerHas<HttpHeaderAttribute>()
                       .WithConstructorArgumentFromControllerAttribute<HttpHeaderAttribute>("name", q => q.Name)
                       .WithConstructorArgumentFromControllerAttribute<HttpHeaderAttribute>("value", q => q.Value);
0

1 Answer 1

3

It would be simpler for you to derive from web api's ActionFiterAttribute class and add the header to the response instead of implementing an action filter from scratch using IActionFilter.

[Edited] For the above scenario, try doing the following:

return continuation().ContinueWith<HttpResponseMessage>((tsk) =>
                {
                    HttpResponseMessage response = tsk.Result;

                    response.Headers.Add(...)

                    return response;

                }, TaskContinuationOptions.OnlyOnRanToCompletion);
Sign up to request clarification or add additional context in comments.

1 Comment

I guess I should of mentioned I am using Ninject, so I have to use this setup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.