c# - 在 Controller 外部将HttpResponseMessage转换为HttpActionResult的最简单方法

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

实现IExceptionHandler时,结果是IHttpActionResult,但是createResponse返回HttpResponseMessage。我只想从请求上下文创建响应消息。它进行内容协商,我希望使用已经存在的东西,而不是自己创建实现IHttpActionResult的自定义模型。

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

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"));

最佳答案

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版本:
  • IHttpActionResult在ASP.NET Core 2中被IActionResult替换:
  • ExceptionHandlerContext位于System.Web.Http中,也不再存在。
    这是详细信息:https://docs.microsoft.com/en-us/aspnet/core/migration/webapi?view=aspnetcore-2.1#migrate-models-and-controllers
  • 关于c# - 在 Controller 外部将HttpResponseMessage转换为HttpActionResult的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51383284/

    相关文章:

    c# - 如何仅验证使用 asp.net web api 上传的图像?

    asp.net-web-api - Breezejs,跨域

    error-handling - Apiglity是否提供内置的错误处理和日志记录?

    web-services - 您可以将错误视为 RESTful API 中的资源吗?

    python - 我已经附上了我的代码。请查看并告诉我错误的原因。解释一下?

    c# - 从 ASP.NET GridView 单元格获取值

    c# - lambda 表达式中的对象范围

    c# - 当前 SDK 版本无法同时使用多个 CloudSpatialAnchorWatcher

    c# - .NET 中的安全 Azure 移动服务 - 如何获取 userId

    c# - 路线在 postman 中工作不正确,不允许邮寄