本文實例講述了MVC利用自定義ModelBinder過濾關鍵字的方法。分享給大家供大家參考,具體如下:
前面一篇主要講解了如何利用ActionFilter過濾關鍵字,這篇主要講解如何利用自己打造的ModelBinder來過濾關鍵字。
首先,我們還是利用上一篇《asp.net MVC利用ActionFilterAttribute過濾關鍵字的方法》中的實體類,但是我們需要加上DataType特性,以便于我們構造的ModelBinder通過DataTypeName識別出來:
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; }
}
}
然后我們新建一個FilterModelBinder的類,其中內容如下:
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行,主要是獲取我們需要驗證的DataTypeName.
第15行,獲取需要驗證的值,然后替換,最后返回即可.
上面做完后,在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了,下面開始測試:

我們輸入的內容如上圖所示,當點擊”添加”按鈕的時候,確彈出如下的錯誤提示:

看來,系統會自動檢測我們的輸入值,發現有非法字符,會彈出錯誤提示,還好我們可以通過web.config配置一下,讓其通過驗證:
打開最外層的Web.config,輸入以下節點:
configuration>
system.web>
httpRuntime requestValidationMode="2.0" />
/system.web>
pages validateRequest="false">
/pages>
/configuration>
然后保存,運行,我們看到,系統成功跑了起來,最后的結果如下:

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