[英]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.