代码之家  ›  专栏  ›  技术社区  ›  Erndob

在控制器外部将httpResponseMessage转换为httpActionResult的最简单方法

  •  0
  • Erndob  · 技术社区  · 6 年前

    实施 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"));
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Dongdong    6 年前

    “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. 在ASP.NET核心2中,IHttpactionResult替换为IActionResult:
    2. exceptionhandlerContext位于system.web.http中,不再存在。 以下是详细信息: https://docs.microsoft.com/en-us/aspnet/core/migration/webapi?view=aspnetcore-2.1#migrate-models-and-controllers