本文實(shí)例講述了MVC利用自定義ModelBinder過濾關(guān)鍵字的方法。分享給大家供大家參考,具體如下:
前面一篇主要講解了如何利用ActionFilter過濾關(guān)鍵字,這篇主要講解如何利用自己打造的ModelBinder來過濾關(guān)鍵字。
首先,我們還是利用上一篇《asp.net MVC利用ActionFilterAttribute過濾關(guān)鍵字的方法》中的實(shí)體類,但是我們需要加上DataType特性,以便于我們構(gòu)造的ModelBinder通過DataTypeName識(shí)別出來:
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)容如下:
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("", "lt;").Replace(">", "gt;");
return result;
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
}
第13行,主要是獲取我們需要驗(yàn)證的DataTypeName.
第15行,獲取需要驗(yàn)證的值,然后替換,最后返回即可.
上面做完后,在Global.asax中,我們需要指定一下:
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ò)誤提示:

看來,系統(tǒng)會(huì)自動(dòng)檢測(cè)我們的輸入值,發(fā)現(xiàn)有非法字符,會(huì)彈出錯(cuò)誤提示,還好我們可以通過web.config配置一下,讓其通過驗(yàn)證:
打開最外層的Web.config,輸入以下節(jié)點(diǎn):
configuration>
system.web>
httpRuntime requestValidationMode="2.0" />
/system.web>
pages validateRequest="false">
/pages>
/configuration>
然后保存,運(yùn)行,我們看到,系統(tǒng)成功跑了起來,最后的結(jié)果如下:

我們可以看到,通過我們自定義的ModelBinder,系統(tǒng)自動(dòng)將非法字符進(jìn)行了替換,非常方便。
MVC中處處AOP,現(xiàn)在我們就可以利用現(xiàn)有的知識(shí)做一個(gè)全局過濾器了。是不是感覺很方便呢?
完整實(shí)例代碼點(diǎn)擊此處本站下載。
希望本文所述對(duì)大家asp.net程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Android深入淺出之Binder機(jī)制
- Android進(jìn)程間通信(IPC)機(jī)制Binder簡(jiǎn)要介紹
- 理解Android系統(tǒng)Binder機(jī)制
- Android4.1中BinderService用法實(shí)例分析
- android IPC之binder通信機(jī)制
- 一個(gè)用xslt樣式將xml解析為xhtml的類TransformBinder(兼容FF和IE7.0)
- 淺談Service Manager成為Android進(jìn)程間通信(IPC)機(jī)制Binder守護(hù)進(jìn)程之路