.NetMVC过滤器

  APS.NET MVC中(以下简称“MVC”)的每一个请求,都会分配给相应的控制器和对应的行为方法去处理,而在这些处理的前前后后如果想再加一些额外的逻辑处理。这时候就用到了过滤器。

  MVC支持的过滤器类型有四种,分别是:Authorization(授权),Action(行为),Result(结果)和Exception(异常)。

如下表,

过滤器类型接口描述
AuthorizationIAuthorizationFilter

此类型(或过滤器)用于限制进入控制器或

控制器的某个行为方法

ExceptionIExceptionFilter

用于指定一个行为,这个被指定的行为处理

某个行为方法或某个控制器里面抛出的异常

Action

 

IActionFilter

 

用于进入行为之前或之后的处理

 

Result

 

IResultFilter用于返回结果的之前或之后的处理

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;

namespace WebMVC.Controllers
{
    public class HomeController : Controller
    {        
       public ActionResult Index()
        {        
            Response.Write("这是动作方法!");
            return View();
        }

        [WebMVC.Filter.MyFilter]
        public ActionResult helo()
        {
            SqlConnection conn = new SqlConnection("错误");
            return View();
        }
    }
}

 

 

 

 

自定义一个过滤器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
namespace WebMVC.Filter { public class MyFilter:FilterAttribute,IExceptionFilter { public void OnException(ExceptionContext filterContext) { //定义日志文件路径 string filePath = filterContext.HttpContext.Server.MapPath(@"\Filter\log.txt"); //写入日志信息 using (StreamWriter sw = File.AppendText(filePath)) { sw.WriteLine("时间:{0}", DateTime.Now.ToString()); sw.WriteLine("控制器:{0}", filterContext.RouteData.Values["Controller"]); sw.WriteLine("动作方法:{0}", filterContext.RouteData.Values["Action"]); sw.WriteLine("异常信息:{0}", filterContext.Exception.Message); } } } }

 

posted on 2019-05-01 20:03 天然灰 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tianranhui/p/10800589.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值