【问题标题】:OData WebApi 2 Error HandlingOData WebApi 2 错误处理
【发布时间】:2016-03-14 04:36:54
【问题描述】:

在我的 Web 服务中,我覆盖了 ExceptionHandler,但我不清楚您将如何格式化异常以符合 OData 错误标准。也许我在接近它是错误的,因为我在网上找不到任何例子。

据我了解,使用 web api 2 有一个全局异常处理的概念,您可以使用自定义 ExceptionHandler 来处理服务中抛出的任何异常。 Exception 仍应使用新的 IHttpActionResult() 更新 ExceptionContext.Result。如何将输入到 IHttpActionResult 的数据格式化为 OData 错误。

下面是 ExceptionHandler 的 sn-p,我一直在纠结如何用正确的 OData HttpResponse 消息覆盖 context.Result。

public class CustomExceptionHandler: ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        HttpResponseMessage msg = context.Request.CreateErrorResponse(HttpStatusCode.NotFound, new ODataError
        {
            ErrorCode = context.Exception.Message,
            Message = context.Exception.InnerException.Message,
            InnerError = new ODataInnerError
            {
                Message = context.Exception.InnerException.Message
            }
        });
        context.Result = //How do you wrap the OData HttpResponseMessage into a IHttpActionResult

    }


}

感谢任何建议, 谢谢, D

【问题讨论】:

  • 您能找到任何解决方案吗?任何提示表示赞赏。谢谢
  • 抱歉,我还没回过神来。当我这样做时,我会更新这个。

标签: exception-handling odata asp.net-web-api2 webapp2 odata-v4


【解决方案1】:
context.Result = new System.Web.Http.Results.ResponseMessageResult(msg);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2015-08-01
    相关资源
    最近更新 更多