繁体   English   中英

MVC4 WebApi在响应标头中添加ETag

[英]MVC4 WebApi adding ETag in Response Header

我们在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;
    }

您可以通过两种方式做到这一点,您可以像这样在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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM