我有一个ASP.NET MVC5项目,当我写错控制器名称时需要处理404页面,例如上帝 /主页/关于 vs坏 /主页/关于
Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException == null)
{
routeData.Values.Add("action", "Index");
}
else //It's an Http Exception, Let's handle it.
{
switch (httpException.GetHttpCode())
{
case 404:
// Page not found.
routeData.Values.Add("action", "HttpError404");
break;
case 500:
// Server error.
routeData.Values.Add("action", "HttpError500");
break;
// Here you can handle Views to other error codes.
// I choose a General error template
default:
routeData.Values.Add("action", "General");
break;
}
}
// Pass exception details to the target error View.
routeData.Values.Add("error", exception);
// Clear the error on server.
Server.ClearError();
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
// Call target Controller and pass the routeData.
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
}
如果我写错了动作我得到了一个错误页面(没关系),但是如果我写错了控制器名称我在浏览器上只得到了简单的html源代码(但是html代码有错误页面但是我在html中得到了文本而不是DOM对象浏览器)
ErrorController
public ActionResult HttpError404(string error)
{
ViewData["Title"] = "Sorry, an error occurred while processing your request. (404)";
ViewData["Description"] = error;
return View("Index");
}
public ActionResult HttpError500(string error)
{
ViewData["Title"] = "Sorry, an error occurred while processing your request. (500)";
ViewData["Description"] = error;
return View("Index");
}
public ActionResult General(string error)
{
ViewData["Title"] = "Sorry, an error occurred while processing your request.";
ViewData["Description"] = error;
return View("Index");
}
THX很多