C#-ASP.NET MVC-架构【1】-自定义错误页

自定义异常本来是一件很简单的事情,没想到在做的过程中遇到各种坑,目前来说,还有Session过期和Ajax请求这两种情况没有特殊处理,其他的基本已经可以使用,等慢慢完善吧。

一、在web.config中新增customErrors节点

  <system.web>
...
<customErrors mode="Off" ></customErrors>
...
</system.web>

二、在Global.asax中注释掉代码行

    protected void Application_Start()
{
...
//FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
...
}

三、在Global.asax中新增方法

    protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.TrySkipIisCustomErrors = true;
Response.Clear(); if (exception != null)
{
string errorpath = this.Context.Request.Path; HttpException httpException = exception as HttpException;
string action = "Index"; if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case :
action = "AccessDenied";
break;
case :
action = "NotFound";
break;
}
} Server.ClearError(); string url = String.Format("~/Error/{0}/?errorpath={1}", action, errorpath);
Response.Redirect(url, true);
}
}

四、新增控制器ErrorController

    public class ErrorController : Controller
{
public ActionResult Index()
{
return View();
} public ActionResult NotFound()
{
return View();
} public ActionResult AccessDenied()
{
return View();
}
}
上一篇:Ubuntu一般软件安装后的路径


下一篇:Linux 网络编程六(socket通信UDP版)