【问题标题】:How to catch or intercept ODataException to return custom error payload如何捕获或拦截 ODataException 以返回自定义错误负载
【发布时间】:2020-09-22 09:03:30
【问题描述】:

我正在重构一个使用 Odata 的 ASP.NET WEB API 解决方案。 在处理错误时,我想提供一个在我的 CustomException 类中定义的自定义错误有效负载。

问题是,当我发出错误请求时,生成的响应是 ODataException 错误有效负载,其中包含一些我不想暴露的机密信息以及堆栈跟踪。

我需要修改此 Odata 有效负载并将其替换为我自己的。

到目前为止,我尝试使用在控制器级别应用的异常过滤器,并尝试在全局级别注册异常处理程序。这些都不起作用。

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net exception asp.net-web-api error-handling odata


    【解决方案1】:

    我可以使用异常过滤器解决它,我之前使用了错误的方法:

    public class CustomExceptionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {    
            ErrorContentResponse error = new ErrorContentResponse();
    
            var response = new HttpResponseMessage(actionExecutedContext.Response.StatusCode)
            {
                Content = new ObjectContent<ErrorContentResponse>(error, new JsonMediaTypeFormatter())
            };
    
            actionExecutedContext.Response = response;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 2020-12-21
      • 2014-03-07
      • 2018-07-14
      • 2023-03-17
      • 1970-01-01
      • 2013-06-09
      相关资源
      最近更新 更多