How to set custom headers when using IHttpActionResult?

前端 未结 7 1356
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 13:31

In ASP.NET Web API 2, the IHttpActionResult offers a lot of value in simplifying controller code and I\'m reluctant to stop using it, but I\'ve hit a problem.

7条回答
  •  无人及你
    2021-02-01 13:48

    This can be achieved with an ActionFilterAttribute, which will examine the response after the controller function but before it goes out, then you can set the attribute on the controller method to add this information, here is my implementation below:

    public class EnableETag : ActionFilterAttribute
    {
    
        /// 
        /// NOTE: a real production situation, especially when it involves a web garden
        ///       or a web farm deployment, the tags must be retrieved from the database or some other place common to all servers.
        /// 
        private static ConcurrentDictionary etags = new ConcurrentDictionary();
    
        public override void OnActionExecuting(HttpActionContext context)
        {
            var request = context.Request;
            if (request.Method == HttpMethod.Get)
            {
                var key = GetKey(request);
                ICollection etagsFromClient = request.Headers.IfNoneMatch;
                if (etagsFromClient.Count > 0)
                {
                    EntityTagHeaderValue etag = null;
                    if (etags.TryGetValue(key, out etag) && etagsFromClient.Any(t => t.Tag == etag.Tag))
                    {
                        context.Response = new HttpResponseMessage(HttpStatusCode.NotModified);
                        SetCacheControl(context.Response);
                    }
                }
            }
        }
        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            var request = context.Request;
            var key = GetKey(request);
            EntityTagHeaderValue etag;
            if (!etags.TryGetValue(key, out etag) || request.Method == HttpMethod.Put ||
            request.Method == HttpMethod.Post)
            {
                etag = new EntityTagHeaderValue("\"" + Guid.NewGuid().ToString() + "\"");
                etags.AddOrUpdate(key, etag, (k, val) => etag);
            }
            context.Response.Headers.ETag = etag;
            SetCacheControl(context.Response);
        }
        private string GetKey(HttpRequestMessage request)
        {
            return request.RequestUri.ToString();
        }
    
        /// 
        /// Defines the time period to hold item in cache (currently 10 seconds)
        /// 
        /// 
        private void SetCacheControl(HttpResponseMessage response)
        {
            response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.FromSeconds(10),
                MustRevalidate = true,
                Private = true
            };
        }
    }
    

    }

提交回复
热议问题