添加标题要在控制器的Web API操作(Add Header To Web API Actions

2019-10-17 09:37发布

我试着去头属性添加到一个控制器,但响应为空与HttpActionContext财产。 难道我做错了什么?

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

Answer 1:

这将是简单的为您从网页API的ActionFiterAttribute类派生和头添加到响应,而不是从头开始实现使用IActionFilter的行为过滤器。

[编辑]对于上述方案,尝试做如下:

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

                    response.Headers.Add(...)

                    return response;

                }, TaskContinuationOptions.OnlyOnRanToCompletion);


文章来源: Add Header To Web API Actions on Controller