本文實(shí)例講述了MVC利用自定義ModelBinder過(guò)濾關(guān)鍵字的方法。分享給大家供大家參考,具體如下:
前面一篇主要講解了如何利用ActionFilter過(guò)濾關(guān)鍵字,這篇主要講解如何利用自己打造的ModelBinder來(lái)過(guò)濾關(guān)鍵字。
首先,我們還是利用上一篇《asp.net MVC利用ActionFilterAttribute過(guò)濾關(guān)鍵字的方法》中的實(shí)體類,但是我們需要加上DataType特性,以便于我們構(gòu)造的ModelBinder通過(guò)DataTypeName識(shí)別出來(lái):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MvcApplication1.Models { public class TestModel { public int TID { get ; set ; } [DataType( "TName" )] public string TName { get ; set ; } [DataType( "TSite" )] public string TSite { get ; set ; } } } |
然后我們新建一個(gè)FilterModelBinder的類,其中內(nèi)容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication1 { public class FilterModelBinder:DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var valueShouldFilter = bindingContext.ModelMetadata.DataTypeName; if (valueShouldFilter == "TName" || valueShouldFilter == "TSite" ) { var resultProvider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (resultProvider != null ) { string result = resultProvider.AttemptedValue; result = result.Replace( "<" , "<" ).Replace( ">" , ">" ); return result; } } return base .BindModel(controllerContext, bindingContext); } } } |
第13行,主要是獲取我們需要驗(yàn)證的DataTypeName.
第15行,獲取需要驗(yàn)證的值,然后替換,最后返回即可.
上面做完后,在Global.asax中,我們需要指定一下:
1
2
3
4
5
6
7
8
9
10
11
|
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ModelBinders.Binders.DefaultBinder = new FilterModelBinder(); } |
這樣,我們就能使用我們自己的ModelBinder了,下面開始測(cè)試:
我們輸入的內(nèi)容如上圖所示,當(dāng)點(diǎn)擊”添加”按鈕的時(shí)候,確彈出如下的錯(cuò)誤提示:
看來(lái),系統(tǒng)會(huì)自動(dòng)檢測(cè)我們的輸入值,發(fā)現(xiàn)有非法字符,會(huì)彈出錯(cuò)誤提示,還好我們可以通過(guò)web.config配置一下,讓其通過(guò)驗(yàn)證:
打開最外層的Web.config,輸入以下節(jié)點(diǎn):
1
2
3
4
5
6
7
|
< configuration > < system.web > < httpRuntime requestValidationMode = "2.0" /> </ system.web > < pages validateRequest = "false" > </ pages > </ configuration > |
然后保存,運(yùn)行,我們看到,系統(tǒng)成功跑了起來(lái),最后的結(jié)果如下:
我們可以看到,通過(guò)我們自定義的ModelBinder,系統(tǒng)自動(dòng)將非法字符進(jìn)行了替換,非常方便。
MVC中處處AOP,現(xiàn)在我們就可以利用現(xiàn)有的知識(shí)做一個(gè)全局過(guò)濾器了。是不是感覺(jué)很方便呢?
完整實(shí)例代碼點(diǎn)擊此處本站下載。
希望本文所述對(duì)大家asp.net程序設(shè)計(jì)有所幫助。