天天看點

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、全局異常過濾器捕獲

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");

筆者原創!如果您覺得閱讀本文對您有幫助,請點一下“推薦”按鈕,您的“推薦”将是我最大的寫作動力!歡迎各位轉載,轉載請添加原部落格連接配接,否則保留追究法律責任的權利,謝謝!

YC.Boilerplate 快速開發架構交流,請加群:1060819005

區塊鍊交流請加QQ群:538327407(已滿),群2:135019400.

我的部落格位址:http://www.cnblogs.com/linbin524/