在Controller上添加标题到Web API操作

时间:2012-11-20 17:11:59

标签: asp.net-mvc http-headers asp.net-web-api

我试图将一个头属性添加到控制器,但使用HttpActionContext属性,Response为null。我做错了吗?

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);

1 个答案:

答案 0 :(得分:3)

从web api的ActionFiterAttribute类派生并将标头添加到响应中而不是使用IActionFilter从头开始实现动作过滤器会更简单。

<强> [编辑] 对于上述场景,请尝试执行以下操作:

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

                    response.Headers.Add(...)

                    return response;

                }, TaskContinuationOptions.OnlyOnRanToCompletion);