How to set custom headers when using IHttpActionResult?

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

    For your scenario, you would need to create a custom IHttpActionResult. Following is an example where I derive from OkNegotiatedContentResult as it runs Content-Negotiation and sets the Ok status code.

    public class CustomOkResult : OkNegotiatedContentResult
    {
        public CustomOkResult(T content, ApiController controller)
            : base(content, controller) { }
    
        public CustomOkResult(T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable formatters) 
            : base(content, contentNegotiator, request, formatters) { }
    
        public string ETagValue { get; set; }
    
        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await base.ExecuteAsync(cancellationToken);
    
            response.Headers.ETag = new EntityTagHeaderValue(this.ETagValue);
    
            return response;
        }        
    }
    

    Controller:

    public class ValuesController : ApiController
    {
        public IHttpActionResult Get()
        {
            return new CustomOkResult(content: "Hello World!", controller: this)
                {
                        ETagValue = "You ETag value"
                };
        }
    }
    

    Note that you can also derive from NegotiatedContentResult, in which case you would need to supply the StatusCode yourself. Hope this helps.

    You can find the source code of OkNegotiatedContentResult and NegotiatedContentResult, which as you can imagine are simple actually.

提交回复
热议问题