MVC异常过滤器 (错误页)

控制器

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());
        }
    }
}




posted on 2017-05-18 11:59  blfbuaa  阅读(237)  评论(0编辑  收藏  举报