【问题标题】:WebApi v2 ExceptionHandler not working with HttpPostWebApi v2 ExceptionHandler 不适用于 HttpPost
【发布时间】:2018-07-26 23:40:22
【问题描述】:

为什么在调用 HTTP 方法发布时从不调用自定义 ExceptionHandler 而是标准响应

这是我的代码

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        //Handler Custom Exception
        config.Services.Replace(typeof(IExceptionHandler), new CustomExceptionHandler());

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new JsonOutputDateTime());
        // Web API routes
        config.MapHttpAttributeRoutes();

        // Remove the XML formatter (Json Only)
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/v1/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

ExceptionHandler.cs

 public class CustomExceptionHandler : System.Web.Http.ExceptionHandling.ExceptionHandler
{
    public override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        SystemExceptionReturn returnObj = new SystemExceptionReturn();
        returnObj.responseCode = "xxxx";
        returnObj.responseMessage = "System Error";     
        var response = context.Request.CreateResponse(HttpStatusCode.OK, returnObj);
        context.Result = new ResponseMessageResult(response);

        return base.HandleAsync(context, cancellationToken);
    }

    public virtual bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true;
    }
    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);
        }
    }
}

Global.asax.xs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        GlobalConfiguration.Configure(WebApiConfig.Register);

    }

}

我的控制器

public class gController : ApiController
{       
    [HttpPost]
    public bool haha(int id)
    {
        bool res = false;
        try
        {
            int ans = id / 0;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return res;
    }       
}

我调用 localhost:xxxx/api/v1/g/haha 时的这个响应

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "Attempted to divide by zero.",
    "ExceptionType": "System.DivideByZeroException"}

但是当我将 HttpPost 更改为 HttpGet 时,它对我有用。

请有人帮助我

对不起我的英语

更新

我发现在 localhost 中的测试不起作用,但是当部署到 IIS 时它起作用 非常感谢您的帮助

【问题讨论】:

  • 您能分享一下您将 POST 更改为 GET 时得到的响应吗?
  • GET 响应 {"responseCode":"xxxx","re​​sponseMessage":"系统错误"}

标签: c# asp.net-web-api exceptionhandler


【解决方案1】:

发送 POST 请求到localhost:xxxx/api/v1/g/haha URL 如果您更改要接收 [FromBody] 的 Id 参数,它将起作用。

        [HttpPost]
        public bool haha([FromBody]int id)
        {
            bool res = false;
            try
            {
                int ans = id / 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return res;
        } 

【讨论】:

  • 发送post请求时是否在body中添加了id参数?
  • 这不是因为 [FromBody] 属性,这更多是已知的 CORS 问题,尽管我同意 OP 没有提供带有查询参数的完整链接,从而导致混淆
猜你喜欢
  • 2014-04-05
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多