【问题标题】:Easiest way to convert HttpResponseMessage to HttpActionResult outside of a controller在控制器之外将 HttpResponseMessage 转换为 HttpActionResult 的最简单方法
【发布时间】:2018-07-17 13:56:46
【问题描述】:

实现IExceptionHandler,结果期待IHttpActionResult,但createResponse返回HttpResponseMessage。我想简单地从请求上下文中创建一个响应消息。它进行内容协商,我更喜欢使用已经存在的东西,而不是自己创建一个实现 IHttpActionResult 的自定义模型。

控制器可以访问帮助器以轻松地将 HttpResponseMessage 转换为 HttpActionResult,但是在控制器之外我找不到任何东西。我最好的选择是什么?

var myCustomException = context.Exception as MyCustomException;

if (myCustomException != null)
{
   context.Result = context.Request.CreateResponse(myCustomException.StatusCode, 
                                                   myCustomException.Error);
   return;
}

context.Result = context.Request.CreateResponse(HttpStatusCode.InternalServerError, 
                                                new MyCustomError("Something went wrong"));

【问题讨论】:

    标签: c# asp.net-web-api error-handling


    【解决方案1】:

    MSDN 页面将为您提供帮助:https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling

    您需要一个全局错误处理程序。这里是核心代码,你可以在 MSDN 页面找到详细信息。

    class OopsExceptionHandler : ExceptionHandler
    {
        public override void HandleCore(ExceptionHandlerContext context)
        {
            context.Result = new TextPlainErrorResult
            {
                Request = context.ExceptionContext.Request,
                Content = "Oops! Sorry! Something went wrong." +
                          "Please contact support@contoso.com so we can try to fix it."
            };
        }
    
        private class TextPlainErrorResult : IHttpActionResult
        {
            public HttpRequestMessage Request { get; set; }
    
            public string Content { get; set; }
    
            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                HttpResponseMessage response = 
                                 new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(Content);
                response.RequestMessage = Request;
                return Task.FromResult(response);
            }
        }
    }
    

    顺便说一句,你应该提到 MVC 版本:

    1. IHttpActionResult 在 ASP.NET Core 2 中被替换为 IActionResult:
    2. ExceptionHandlerContext 在 System.Web.Http 中,也不再存在。 这是详细信息:https://docs.microsoft.com/en-us/aspnet/core/migration/webapi?view=aspnetcore-2.1#migrate-models-and-controllers

    【讨论】:

    • 是的,我看到了。最终为 HttpResponseMessage 创建了我自己的包装器。如果有一种方法可以在没有我自己的包装器的情况下将 HttpResponseMessage 转换为 HttpActionResult (通过 .NET),我很感兴趣。如何在 ApiController 中做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2012-09-02
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2019-08-14
    相关资源
    最近更新 更多