在ASP.NET MVC中,可以通过以下方式来定制和管理错误。
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values["controller"] = "Error";
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values["action"] = "NotFound";
break;
// 添加其他错误处理的情况
}
}
else
{
routeData.Values["action"] = "Index";
}
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
public class ErrorController : Controller
{
public ViewResult Index()
{
return View("Error");
}
public ViewResult NotFound()
{
Response.StatusCode = 404;
return View("NotFound");
}
// 添加其他错误处理的动作方法
}
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
Error
@Model.Exception.Message
@Html.ActionLink("返回首页", "Index", "Home")
@{
ViewBag.Title = "Not Found";
}
Not Found
The resource you requested could not be found.
@Html.ActionLink("返回首页", "Index", "Home")
通过以上步骤,可以对ASP.NET MVC中的错误进行定制和管理,并根据不同的错误类型显示相应的视图。