控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC过滤器.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index(string id, string name)
{
int a = 1;
int b = 0;
int c = a / b; //这里人为的搞一个错误。
return View();
}
public ActionResult Error()
{
return View();
}
}
}
Home控制器下的的Error视图
@{
Layout = null;
}
@model HandleErrorInfo
@*这个HandleErrorInfo实体类里面就是当前最后一次错误的详细信息*@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
</head>
<body>
<div>
@Model.ActionName;
@Model.ControllerName;
@Model.Exception.Message;
</div>
</body>
</html>
在项目下建一个Filters的文件夹,用来放过滤器。
在Filters文件夹下面新建一个ExceptionAttribute.cs异常过滤器类,让它继承HandleErrorAttribute类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC过滤器.Filters
{
public class ExceptionAttribute:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
//获取抛出异常的对象
Exception ex = filterContext.Exception;
//写日记
System.IO.File.AppendAllText(filterContext.HttpContext.Server.MapPath("/Logs/Log.txt"), ex.ToString());
//如果这里设为false,就表示告诉MVC框架,我没有处理这个错误。然后让它跳转到自己定义的错误页(设为true的话,就表示告诉MVC框架,异常我已经处理了。不需要在跳转到错误页了,也部会抛出黄页了)
filterContext.ExceptionHandled = false;
}
}
}
去到APP_Start文件夹下的FilterConfig.cs类中,去将自己定义的ExceptionAttribute异常过滤器注册为全局过滤器
using MVC过滤器.Filters;
using System.Web;
using System.Web.Mvc;
namespace MVC过滤器
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
//将自己定义的异常过滤器注册为全局过滤器。(全局过滤器是可以注册多个的)
filters.Add(new ExceptionAttribute());
}
}
}