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




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值