MVC4 Web Api在响应标头中添加ETag

时间:2012-07-18 09:14:17

标签: c# .net asp.net-mvc-4 response etag

我们在Mvc4中创建了一个REST服务 我试图在我的WebApi方法的响应中添加ETag标头。它被添加到Header集合中而没有任何错误,但是当我检查Fiddler中的响应头时它不在那里。

以下是我在响应中编写标题的方法:

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

1 个答案:

答案 0 :(得分:4)

你可以用2种方法做,你可以在ActionFilter.OnActionExecuted方法中设置ETag,如下所示:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
    actionExecutedContext.ActionContext.Response.Headers.ETag = new EntityTagHeaderValue(...);
}

但是没有办法轻松地将所需的值从控制器传递给ActionFilter。第二种方法是更改​​WebAPI操作。而不是返回模型类型,返回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;
}