How to set custom headers when using IHttpActionResult?

前端 未结 7 1355
爱一瞬间的悲伤
爱一瞬间的悲伤 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 14:03

    Here is a solution I use in my common Web API 2 library code that can easily support setting any headers--or any other properties on the HttpResponseMessage provided in ExecuteAsync--without being tied to any specific derived NegotiatedContentResult implementation:

    public class FlexibleNegotiatedContentResult<T> : NegotiatedContentResult<T>
    {
        private readonly Action<HttpResponseMessage> _responseMessageDelegate;
    
        public FlexibleNegotiatedContentResult(HttpStatusCode statusCode, T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
            : base(statusCode, content, contentNegotiator, request, formatters)
        {
        }
    
        public FlexibleNegotiatedContentResult(HttpStatusCode statusCode, T content, ApiController controller, Action<HttpResponseMessage> responseMessageDelegate = null)
            : base(statusCode, content, controller)
        {
            _responseMessageDelegate = responseMessageDelegate;
        }
    
        public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage responseMessage = await base.ExecuteAsync(cancellationToken);
    
            if (_responseMessageDelegate != null)
            {
                _responseMessageDelegate(responseMessage);
            }
    
            return responseMessage;
        }
    }
    

    and an example usage:

    new FlexibleNegotiatedContentResult<string>(HttpStatusCode.Created, "Entity created!", controller, response => response.Headers.Location = new Uri("https://myapp.com/api/entity/1"));
    
    0 讨论(0)
提交回复
热议问题