如何处理 ASP.NET MVC5 中操作不受支持的 HTTP 方法?
How to handle unsupported HTTP methods on actions in ASP.NET MVC5?
如何处理对存在的操作的请求,但不支持请求中的 http 方法?
比如我有以下操作:
[HttpGet]
[Route("~/")]
[Route("ServiceVisits")]
public ActionResult Index()
{
return View();
}
如果 GET
请求到达 http://localhost:59949/
或 http://localhost:59949/ServiceVisits
则我们返回页面,但如果 POST
请求到达,那么我会在我必须处理 Global.asax.cs
中的 Application_Error
方法。
请求不存在的操作将return一个404
页面,因为我有以下路线:
routes.MapRoute(
"PageNotFound",
"{*.*}",
new {controller = "Error", action = "NotFound"}
);
我正在使用属性路由,上面的约定是我处理 404 的唯一约定。
我只想在 Application_Error
中记录严重的系统错误,而不是 No matching action was found on controller
异常。谢谢!
最后我决定简单地检查 Application_Error
中的 404 并避免记录这些错误,如下所示:
protected void Application_Error()
{
var ex = Server.GetLastError();
if (ex is HttpException httpEx)
{
var httpCode = httpEx.GetHttpCode();
Context.Response.StatusCode = httpCode;
if (httpCode != (int) HttpStatusCode.NotFound)
{
Logger.Error(ex, "Unhandled HttpException in Application_Error");
}
}
else
{
Context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
Logger.Fatal(ex, "Unhandled exception in Application_Error");
}
Context.Server.ClearError();
Context.Response.TrySkipIisCustomErrors = true;
}
如何处理对存在的操作的请求,但不支持请求中的 http 方法?
比如我有以下操作:
[HttpGet]
[Route("~/")]
[Route("ServiceVisits")]
public ActionResult Index()
{
return View();
}
如果 GET
请求到达 http://localhost:59949/
或 http://localhost:59949/ServiceVisits
则我们返回页面,但如果 POST
请求到达,那么我会在我必须处理 Global.asax.cs
中的 Application_Error
方法。
请求不存在的操作将return一个404
页面,因为我有以下路线:
routes.MapRoute(
"PageNotFound",
"{*.*}",
new {controller = "Error", action = "NotFound"}
);
我正在使用属性路由,上面的约定是我处理 404 的唯一约定。
我只想在 Application_Error
中记录严重的系统错误,而不是 No matching action was found on controller
异常。谢谢!
最后我决定简单地检查 Application_Error
中的 404 并避免记录这些错误,如下所示:
protected void Application_Error()
{
var ex = Server.GetLastError();
if (ex is HttpException httpEx)
{
var httpCode = httpEx.GetHttpCode();
Context.Response.StatusCode = httpCode;
if (httpCode != (int) HttpStatusCode.NotFound)
{
Logger.Error(ex, "Unhandled HttpException in Application_Error");
}
}
else
{
Context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
Logger.Fatal(ex, "Unhandled exception in Application_Error");
}
Context.Server.ClearError();
Context.Response.TrySkipIisCustomErrors = true;
}