MVC 自定义过滤器

常规过滤器,及过滤器与特性这类关系请自己学习,以下是实用中的几个demo,主要有(过滤器在controller的使用,自定义,全局过滤器)

1、控制器中的使用

//
// GET: /TestAttribute/
/// <summary>
///可以查看当前Controller 具体内容,当前请求,还有HttpContext。
///过滤器就像是一个类一样,标识就像是实例化,执行,只是有着具体执行前执行后的过滤差异执行action之前,先过滤
/// </summary>
/// <returns></returns>
[MyActionFilter(NameAttrbute = "Index")]//自定义过滤器
public ActionResult Index()
{
string str=this.HttpContext.Application.ToString();
HttpContextBase httpBaseText = HttpContext;
string[] acceptType=new string[10];

for (int t = 0; t < this.HttpContext.Request.AcceptTypes.Count(); t++) {

acceptType[t]=this.HttpContext.Request.AcceptTypes[t];
Response.Write("当前请求的http详细:序号【" + t + "】" + acceptType[t] + "</br>");

}
Response.Write("当前请求路由:" + this.RouteData + "</br>");

return View();
}

2、具体过滤器的定义

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

namespace MvcAppMSDNStudyDemo
{
#region MyRegion
///
///1、泛型约束,先继承的类和接口,接下来才是where T: 具体过滤 ,具体内容参考泛型
///
/// 自定义过滤器 action级别
///
/// public class MyActionFilterAttribute<T> : IActionFilter, IResultFilter
/// where T: class,IEnumerable, new()//泛型约束
///
///2、过滤器种类有四大类 Auther过滤器(身份验证),Action, Result,异常handerError过滤器(要在异常发生是调用),
///3、过滤器级别 全局过滤器 要在FilterConfig中注册,就像路由要在Gloax注册,实际上就是对整个生命周期Aop流程拓展,过滤器有点像AOP
///action级别的过滤器,类过滤器,全局过滤器大概就这样
#endregion

/// <summary>
/// 过滤器统一命名结尾要有Attribute,就像我们的Controller,标识过滤器,要继承相应的过滤器,过滤器,还
/// 当请求某个具体action的时候,它有自己的过滤器,那么它就只执行自己的过滤器,过滤器就忽略了,要全部实现的话,就要采用特定属性标识我们自定义的过滤器
/// </summary>
[AttributeUsage(AttributeTargets.All,AllowMultiple=true)]//这个就是所有都可以过滤了
public class MyActionFilterAttribute : ActionFilterAttribute //要继承对应的过滤器,本质就是特性
{
private string nameAttrbute;
public string NameAttrbute {//对自定义的属性采用封装

get { return nameAttrbute; }
set { this.nameAttrbute = value; }
}
public int index = 0;
//
// 摘要:
// 在执行操作方法之前由 ASP.NET MVC 框架调用。
//
// 参数:
// filterContext:
// 筛选器上下文。
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
index++;//输出接口都是1,这是每次结构都在过滤都在调用
//特定Http请求输出
HttpContext.Current.Response.Write(index+" 过滤器级别:" +this.nameAttrbute+"</br>");
HttpContext.Current.Response.Write(index+" 当前过滤器时间戳=" + filterContext.HttpContext.Timestamp + "</br>");
base.OnActionExecuting(filterContext);

}
}
}

3、全局异常过滤器捕获

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

namespace MvcAppMSDNStudyDemo.FilterAttrbute
{
public class HanderErrorFilterAttribute:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
HttpContext.Current.Response.Write("这里异常捕获了");


HttpContext.Current.Response.Redirect("/TestAttribute/Index");
}
}
}

原文地址:https://www.cnblogs.com/linbin524/p/4767054.html