WebApi v2 ExceptionHandler无法使用HttpPost

时间:2018-02-16 05:07:47

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

如何调用自定义ExceptionHandler,而不是调用HTTP方法发布时的标准响应

这是我的代码

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时,它会发生。工作的 非常感谢你的帮助

1 个答案:

答案 0 :(得分:-1)

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

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