How to set custom headers when using IHttpActionResult?

前端 未结 7 1364
爱一瞬间的悲伤
爱一瞬间的悲伤 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 : NegotiatedContentResult
    {
        private readonly Action _responseMessageDelegate;
    
        public FlexibleNegotiatedContentResult(HttpStatusCode statusCode, T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable formatters)
            : base(statusCode, content, contentNegotiator, request, formatters)
        {
        }
    
        public FlexibleNegotiatedContentResult(HttpStatusCode statusCode, T content, ApiController controller, Action responseMessageDelegate = null)
            : base(statusCode, content, controller)
        {
            _responseMessageDelegate = responseMessageDelegate;
        }
    
        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage responseMessage = await base.ExecuteAsync(cancellationToken);
    
            if (_responseMessageDelegate != null)
            {
                _responseMessageDelegate(responseMessage);
            }
    
            return responseMessage;
        }
    }
    

    and an example usage:

    new FlexibleNegotiatedContentResult(HttpStatusCode.Created, "Entity created!", controller, response => response.Headers.Location = new Uri("https://myapp.com/api/entity/1"));
    

提交回复
热议问题