问题描述
我有一些基本的代码来确定我的 MVC 应用程序中的错误.目前在我的项目中,我有一个名为 Error
的控制器,带有操作方法 HTTPError404()
、HTTPError500()
和 General().它们都接受一个字符串参数
error
.使用或修改下面的代码.将数据传递给错误控制器进行处理的最佳/正确方法是什么?我想要一个尽可能强大的解决方案.
I have some basic code to determine errors in my MVC application. Currently in my project I have a controller called
Error
with action methods HTTPError404()
, HTTPError500()
, and General()
. They all accept a string parameter error
. Using or modifying the code below.What is the best/proper way to pass the data to the Error controller for processing? I would like to have a solution as robust as possible.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
switch (httpException.GetHttpCode())
{
case 404:
// page not found
routeData.Values.Add("action", "HttpError404");
break;
case 500:
// server error
routeData.Values.Add("action", "HttpError500");
break;
default:
routeData.Values.Add("action", "General");
break;
}
routeData.Values.Add("error", exception);
// clear error on server
Server.ClearError();
// at this point how to properly pass route data to error controller?
}
}
推荐答案
与其为此创建新路由,您只需重定向到控制器/操作并通过查询字符串传递信息.例如:
Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:
protected void Application_Error(object sender, EventArgs e) {
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null) {
string action;
switch (httpException.GetHttpCode()) {
case 404:
// page not found
action = "HttpError404";
break;
case 500:
// server error
action = "HttpError500";
break;
default:
action = "General";
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
}
然后你的控制器会收到你想要的任何东西:
Then your controller will receive whatever you want:
// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
return View("SomeView", message);
}
您的方法有一些权衡.在这种错误处理中循环时要非常小心.另一件事是,由于您正在通过 asp.net 管道来处理 404,您将为所有这些点击创建一个会话对象.对于频繁使用的系统来说,这可能是一个问题(性能).
There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the asp.net pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavily used systems.
这篇关于ASP.NET MVC 自定义错误处理 Application_Error Global.asax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!