[英]WebApi v2 ExceptionHandler not working with HttpPost
为什么从不调用自定义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时却正常工作,非常感谢您的帮助
要将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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.