[英]MVC4 WebApi adding ETag in Response Header
We have a REST Service created in Mvc4 I am trying to add ETag Header in the Response from my WebApi method. 我们在Mvc4中创建了一个REST服务,我试图在WebApi方法的响应中添加ETag标头。 It is added in the Header collection without any error but when I check the response header in the Fiddler it is not there. 它被添加到Header集合中,没有任何错误,但是当我检查Fiddler中的响应头时,它不存在。
Here is the method that I used to write header in the response: 这是我用来在响应中写标头的方法:
internal static HttpResponseMessage<T> GetResponse<T>(Tuple<T, Dictionary<string, string>> response)
{
HttpResponseMessage<T> httpResponse = new HttpResponseMessage<T>(response.Item1, HttpStatusCode.OK);
if (response.Item2 != null)
{
foreach (var responseHeader in response.Item2)
{
if (string.Compare(responseHeader.Key, "ETAG", StringComparison.OrdinalIgnoreCase) == 0)
{
httpResponse.Headers.ETag = new System.Net.Http.Headers.EntityTagHeaderValue("\"" + responseHeader.Value + "\"");
}
else
{
httpResponse.Headers.Add(responseHeader.Key, responseHeader.Value);
}
}
}
return httpResponse;
}
You can do it 2 ways, you can either set the ETag in an ActionFilter.OnActionExecuted method like this: 您可以通过两种方式做到这一点,您可以像这样在ActionFilter.OnActionExecuted方法中设置ETag:
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
actionExecutedContext.ActionContext.Response.Headers.ETag = new EntityTagHeaderValue(...);
}
But there's no way to easily pass the desired value from your controller to the ActionFilter. 但是无法将所需的值轻松地从控制器传递到ActionFilter。 The second way is to change your WebAPI Action. 第二种方法是更改您的WebAPI操作。 Instead of returning a model type, return an HttpResponseMessage: 而不是返回模型类型,而是返回HttpResponseMessage:
[HttpGet]
public HttpResponseMessage MyActionMethod() {
var result = // response data
var response = Request.CreateResponse<MyType>(HttpStatusCode.OK, result);
response.Headers.Add("Last Modified", result.Modified.ToString("R"));
response.Headers.ETag = new System.Net.Http.Headers.EntityTagHeaderValue(CreateEtag(result));
return response;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.