在Controller上添加标题到Web API操作 [英] Add Header To Web API Actions on Controller
本文介绍了在Controller上添加标题到Web API操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将一个头属性添加到控制器,但使用HttpActionContext属性,Response为null。我做错了吗?
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);
推荐答案
从web api派生出来会更简单ActionFiterAttribute类并将标头添加到响应中,而不是使用IActionFilter从头开始实现动作过滤器。
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.
[已编辑]
在上面的场景中,尝试执行以下操作:
For the above scenario, try doing the following:
return continuation().ContinueWith<HttpResponseMessage>((tsk) =>
{
HttpResponseMessage response = tsk.Result;
response.Headers.Add(...)
return response;
}, TaskContinuationOptions.OnlyOnRanToCompletion);
这篇关于在Controller上添加标题到Web API操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文