【问题标题】:400 Bad Request not going through custom exception handler400 Bad Request 未通过自定义异常处理程序
【发布时间】:2016-09-02 03:23:07
【问题描述】:

这个 400 Bad Request 没有通过我的异常处理程序:

{
  "message": "The request is invalid.",
  "messageDetail": "The parameters dictionary contains a null entry for parameter 'subscriptionId' of non-nullable type 'System.Guid' for method 'System.Net.Http.HttpResponseMessage Get(System.Guid)' in 'Product.Controllers.ItemController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}

在我的WebApiConfig.cs 我有这个:

config.Services.Replace(typeof(IExceptionHandler), new HttpExceptionHandler());

从操作、存储库、服务层级别抛出的每个异常都由此异常处理程序处理。但是对于这个错误,通用的 WebApi 异常处理程序会启动。

我应该如何解决这个问题才能让这个异常通过我的异常处理程序?

【问题讨论】:

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


    【解决方案1】:

    我有同样的问题,这里是我的解决方案

    1- 添加过滤器

    public class RequestNoValidoAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    RequestMessage = actionContext.Request,
                    Content = new StringContent("Formato no válido.")
                };
                actionContext.Response = response;
            }
        }
    }
    

    2- 在您的 WebApiConfig.cs 中添加过滤器

    config.Filters.Add(new RequestNoValidoAttribute());
    

    【讨论】:

      猜你喜欢
      • 2019-03-19
      • 2014-05-06
      • 1970-01-01
      • 2023-03-07
      • 2017-05-08
      • 1970-01-01
      • 2021-10-19
      • 2011-07-13
      • 2015-10-18
      相关资源
      最近更新 更多