How to set custom headers when using IHttpActionResult?

前端 未结 7 1358
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  梦毁少年i
    2021-02-01 13:38

    public static class HttpExtentions
    {
        public static IHttpActionResult AddHeader(this IHttpActionResult action,
            string headerName, IEnumerable headerValues)
        {
            return new HeaderActionResult(action, headerName, headerValues);
        }
    
        public static IHttpActionResult AddHeader(this IHttpActionResult action,
            string headerName, string header)
        {
            return AddHeader(action, headerName, new[] {header});
        }
    
        private class HeaderActionResult : IHttpActionResult
        {
            private readonly IHttpActionResult action;
    
            private readonly Tuple> header;
    
            public HeaderActionResult(IHttpActionResult action, string headerName,
                IEnumerable headerValues)
            {
                this.action = action;
    
                header = Tuple.Create(headerName, headerValues);
            }
    
            public async Task ExecuteAsync(CancellationToken cancellationToken)
            {
                var response = await action.ExecuteAsync(cancellationToken);
    
                response.Headers.Add(header.Item1, header.Item2);
    
                return response;
            }
        }
    }
    

提交回复
热议问题