1

为什么在调用 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 }
        );
    }
}

异常处理程序.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);
        }
    }
}

全球.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 时它起作用了 非常感谢您的帮助

4

1 回答 1

-1

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

        [HttpPost]
        public bool haha([FromBody]int id)
        {
            bool res = false;
            try
            {
                int ans = id / 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return res;
        } 
于 2018-02-16T06:58:14.620 回答