简体   繁体   中英

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. It is added in the Header collection without any error but when I check the response header in the Fiddler it is not there.

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:

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. The second way is to change your WebAPI Action. Instead of returning a model type, return an 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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