csharp 包装WebApi IHttpActionResult以向控制器公开响应消息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 包装WebApi IHttpActionResult以向控制器公开响应消息相关的知识,希望对你有一定的参考价值。

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace SampleApi.Results
{
    public class WrappedHttpActionResult : IHttpActionResult
    {
        private IHttpActionResult _innerResult;
        private string _responsePhrase;
        private Action<HttpResponseMessage> _responseAction;

        public WrappedHttpActionResult(IHttpActionResult inner, Action<HttpResponseMessage> responseAction)
            : this(inner, null, responseAction)
        {
        }

        public WrappedHttpActionResult(IHttpActionResult inner, string responsePhrase, Action<HttpResponseMessage> responseAction = null)
        {
            _innerResult = inner;
            _responsePhrase = responsePhrase;
            _responseAction = responseAction;
        }

        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = await _innerResult.ExecuteAsync(cancellationToken);            
            if (!string.IsNullOrWhiteSpace(_responsePhrase))
            {
                response.ReasonPhrase = _responsePhrase;
            }
            if (_responseAction != null)
            {
                _responseAction(response);
            }            
            return response;
        }       
    }
}
using System.Net.Http.Headers;
using System.Web.Http;

namespace SampleApi.Controllers
{
    public class ValuesController : ApiController
    {
        public IHttpActionResult Get(int id)
        {
            //404 with custom reason phrase
            if (id < 1)
                return NotFound().With("Could not find object");

            //200 with ETag
            var response = new { id = id, name = "xyz" };
            return Ok(response).With(x => x.Headers.ETag = new EntityTagHeaderValue(@"""etag"""));
        }
    }
}
using SampleApi.Results;
using System;
using System.Net.Http;
using System.Web.Http;

namespace SampleApi
{
    public static class IHttpActionResultExtensions
    {
        public static IHttpActionResult With(this IHttpActionResult inner, string responsePhrase = null, Action<HttpResponseMessage> responseAction = null)
        {
            return new WrappedHttpActionResult(inner, responsePhrase, responseAction);
        }

        public static IHttpActionResult With(this IHttpActionResult inner, Action<HttpResponseMessage> responseAction)
        {
            return new WrappedHttpActionResult(inner, responseAction);
        }
    }
}

以上是关于csharp 包装WebApi IHttpActionResult以向控制器公开响应消息的主要内容,如果未能解决你的问题,请参考以下文章

csharp 自动WebAPI lowerCase序列化。

csharp RouteTestingExtensions仅限WebAPI

csharp 常见的webapi配置

csharp #c##webapi klient do mediqusa

csharp 标准脚手架读写WebApi控制器

csharp Web Api枚举验证属性。 #webapi,#enum