MVC入門學習筆記(六)

2021-05-23 00:19:27 字數 2478 閱讀 7805

五 過濾器filter

本章引用重典對於

filter的講解

判斷登入與否或使用者許可權

決策輸出快取

防盜煉

防蜘蛛

本地化與國際化設定 

實現動態action

filter是一種宣告式程式設計方式,在asp.net mvc中它只能限制於action(或它的controller)。

filter要繼承於actionfilterattribute抽象類,並可以覆寫void onactionexecuting(actionexecutingcontext)和

void onactionexecuted(actionexecutedcontext)

以及void onresultexecuting(resultexecutingcontext)和

void onresultexecuted(resultexecutedcontext)

onactionexecuting是action執行前的操作,onactionexecuted則是action執行後的操作

而onresultexecuting是解析actionresult前執行,onresultexecuted是解析actionresult後執行。

下面我給大家乙個示例,來看看它的的執行順序

首先我們先建立 乙個filter,名字叫做testfilter

public

class testfilter : actionfilterattribute

public

override

void onactionexecuted(actionexecutedcontext filtercontext)

public

override

void onresultexecuting(resultexecutingcontext filtercontext)

public

override

void onresultexecuted(resultexecutedcontext filtercontext)

}

然後建立乙個action:

[testfilter]//將此filter應用於action

public actionresult filteraction()

在它的view中寫入:

<%session["temp"] += "view execute<

br/>"; %>

最後在其它頁面得到session["temp"]的輸出結果:

testfilter onactionexecuting

testfilter onactionexecuted

testfilter onresultexecuting

view execute

testfilter onresultexecuted

由此可得到它們的執行順序也是如上

將filter應用在controller上有2種方式

1.直接將filter應用在controller上,如:

[testfilter]

public

class eicecontroller : controller

2.重寫controller內的

onactionexecuting/onactionexecuted/onresultexecuting/onresultexecuted的四個方法。

下面我們說幾個系統的filter

規定頁面的訪問形式,如

頁面只能以post形式訪問,即表單提交。

規定action的名稱。

應用場景:如果不想用方法名做為action名,或action名為關鍵字的話,如

[actionname("class")]

public actionresult example()

當前方法僅是普通方法不解析為action

為action新增快取

[outputcache(duration = 60, varybyparam = "*")]

public actionresult example()

該action可以接受html等危險**(asp.net mvc在aspx中設定<%@ page 的屬性無法完成等同任務。)

[validateinput(false)]

public actionresult example()

用於驗證伺服器篡改。

[validateantiforgerytoken]

public actionresult example()

MVC學習筆記

一,如果是虛擬伺服器的話,那得這麼配置 4.注意 將1標的規則更改為 mvc 即可 自行支援 iis6 and iis7 兩種模式 筆者注 一般的虛擬主機不支援.mvc,aspx也要檢查檔案存在 變通方法為可以將.mvc換成.ashx或.asbx 二,url的變革 post.aspx?year 19...

MVC學習筆記

mvc採用的是 方法繫結檢視 就是說方法的名字會對應乙個特定頁面的名字,它們的名字要一致。1 引用domain 域 因為mvc的domain一般都方法在models中。using 解決方案名稱.models 2 viewbag,在方法中配置該引數的值,即可在檢視中獲取,注意的是引數名稱要一致 在co...

MVC學習筆記

一 什麼是mvc v 是view 檢視 代表與使用者互動介面。m 是model 模型層 業務流程 狀態的處理以及業務規則的制定。模型層接受檢視層的請求,並返回最終的處理結果。c 是controller 控制層 分發,決定使用哪個模型,返回哪個檢視。二 springmvc dispatcherserv...