Exception 从Asp.NETWebAPI向邮递员检索自定义异常

Exception 从Asp.NETWebAPI向邮递员检索自定义异常,exception,asp.net-web-api2,postman,Exception,Asp.net Web Api2,Postman,我们已经创建了自定义异常类,它包含一些我们需要从WebAPI返回的信息。现在,当我们将数据返回给Postman时,自定义异常将被基异常类覆盖 这是我们现在得到的输出: 我们需要邮递员提供的信息 我认为您在实现自定义类时犯了错误。下面是自定义异常类的示例实现 public class APIExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActio

我们已经创建了自定义异常类,它包含一些我们需要从WebAPI返回的信息。现在,当我们将数据返回给Postman时,自定义异常将被基异常类覆盖

这是我们现在得到的输出:

我们需要邮递员提供的信息


我认为您在实现自定义类时犯了错误。下面是自定义异常类的示例实现

 public class APIExceptionFilter : ExceptionFilterAttribute
    {
            public override void OnException(HttpActionExecutedContext actionExecutedContext)
               {
                     // Assign the status code that you want as output
                       HttpStatusCode status = HttpStatusCode.InternalServerError;
                       string messageToBeDisplayed = "TestMessage";
                       actionExecutedContext.Response = new HttpResponseMessage { StatusCode = status, Content = new StringContent( messageToBeDisplayed , System.Text.Encoding.UTF8) };
                       base.OnException(actionExecutedContext);

               }
    }
在“WebApiConfig”类和“Register”方法中,您需要添加“apieexceptionfilter”过滤器,如下所示,因为它将为所有请求注册它:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
              // Add this......
              config.Filters.Add(new APIExceptionFilter());
        }
    }

@如果你觉得答案有用,请接受