Add Header To Web API Actions on Controller

社会主义新天地 提交于 2019-12-13 17:25:02

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/13478420/add-header-to-web-api-actions-on-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!