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

时间:2018-07-17 13:56:47

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

实施Trim()时,结果期望<script type="mce-mce-mce-mce-mce-mce-mce-mce-mce-mce-mce-mce-mce-mce-mce- mce-mce-mce-mce-mce-mce-mce-mce-mce-mce-mce-text/javascript" language="JavaScript">// <![CDATA[ function ShowHide(divId) { if(document.getElementById(divId).style.display == 'none') { document.getElementById(divId).style.display='block'; } else { document.getElementById(divId).style.display = 'none'; } } // ]]></script> <a href="javascript:;" onclick="javascript:ShowHide('HiddenDiv')">Read more</a></p> <div id="HiddenDiv" class="mid" style="display: none; text-align: justify;"> <script type="text/javascript" language="JavaScript">// <![CDATA[ function ShowHide(divId) { if(document.getElementById(divId).style.display == 'none') { document.getElementById(divId).style.display='block'; } else { document.getElementById(divId).style.display = 'none'; } } // ]]></script> </p> ,但是IExceptionHandler返回IHttpActionResult。我只想从请求上下文创建响应消息。它进行内容协商,我希望使用已经存在的东西,而不是自己创建实现IHttpActionResult的自定义模型。

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

createResponse

1 个答案:

答案 0 :(得分:0)

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 Core 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