上一篇主要讲解了如何利用ActionFilter过滤关键字,这篇主要讲解如何利用自己打造的ModelBinder来过滤关键字。

首先,我们还是利用上一篇中的实体类,但是我们需要加上DataType特性,以便于我们构造的ModelBinder通过DataTypeName识别出来:

   1:  using System.ComponentModel.DataAnnotations;
   2:  using System.Web.Mvc;
   3:   
   4:  namespace MvcApplication1.Models
   5:  {
   6:      public class TestModel
   7:      {
   8:          public int TID { get; set; }
   9:   
  10:          [DataType("TName")]
  11:          public string TName { get; set; }
  12:   
  13:          [DataType("TSite")]
  14:          public string TSite { get; set; }
  15:      }
  16:  }

然后我们新建一个FilterModelBinder的类,其中内容如下:

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.Mvc;
   6:   
   7:  namespace MvcApplication1
   8:  {
   9:      public class FilterModelBinder:DefaultModelBinder
  10:      {
  11:          public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
  12:          {
  13:              var valueShouldFilter = bindingContext.ModelMetadata.DataTypeName;
  14:              if (valueShouldFilter == "TName" || valueShouldFilter == "TSite")
  15:              {
  16:                  var resultProvider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  17:                  if (resultProvider != null)
  18:                  {
  19:                      string result = resultProvider.AttemptedValue;
  20:                      result = result.Replace("<", "&lt;").Replace(">", "&gt;");
  21:                      return result;
  22:                  }
  23:              }
  24:   
  25:              return base.BindModel(controllerContext, bindingContext);
  26:          }
  27:      }
  28:  }

第13行,主要是获取我们需要验证的DataTypeName.

第15行,获取需要验证的值,然后替换,最后返回即可.

上面做完后,在Global.asax中,我们需要指定一下:

   1:  protected void Application_Start()
   2:          {
   3:              AreaRegistration.RegisterAllAreas();
   4:   
   5:              WebApiConfig.Register(GlobalConfiguration.Configuration);
   6:              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   7:              RouteConfig.RegisterRoutes(RouteTable.Routes);
   8:              BundleConfig.RegisterBundles(BundleTable.Bundles);
   9:   
  10:              ModelBinders.Binders.DefaultBinder = new FilterModelBinder();
  11:          }

这样,我们就能使用我们自己的ModelBinder了,下面开始测试:

我们输入的内容如上图所示,当点击”添加”按钮的时候,确弹出如下的错误提示:

看来,系统会自动检测我们的输入值,发现有非法字符,会弹出错误提示,还好我们可以通过web.config配置一下,让其通过验证:

打开最外层的Web.config,输入以下节点:

   1:  <configuration>
   2:    <system.web>
   3:     <httpRuntime requestValidationMode="2.0" />
   4:    </system.web>
   5:    <pages validateRequest="false">
   6:    </pages>
   7:  </configuration>

然后保存,运行,我们看到,系统成功跑了起来,最后的结果如下:

我们可以看到,通过我们自定义的ModelBinder,系统自动将非法字符进行了替换,非常方便。

MVC中处处AOP,现在我们就可以利用现有的知识做一个全局过滤器了。是不是感觉很方便呢?

百度网盘源代码下载

微云源代码下载

2014.04.26更新

由于上面的例子不能体现其通用性,毕竟我们定义了一个TSite的datatype和一个TName的datatype。

其实我们完全可以给需要过滤的字段加上一个 [DataType("ShouldBeFilter")]的定义,这样无论是什么实体,只要包含了这个定义,都可以被过滤掉关键字了:

实体类定义:

 public class TestModel
{
public int TID { get; set; } [DataType("ShouldBeFilter")]
public string TName { get; set; } [DataType("ShouldBeFilter")]
public string TSite { get; set; }
}

通用过滤方法:

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 == "ShouldBeFilter")
{
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);
}
}
}

MVC中利用自定义的ModelBinder过滤关键字的更多相关文章

  1. Asp.net Mvc中利用ValidationAttribute实现xss过滤

    在网站开发中,需要注意的一个问题就是防范XSS攻击,Asp.net mvc中已经自动为我们提供了这个功能.用户提交数据时时,在生成Action参数的过程中asp.net会对用户提交的数据进行验证,一旦 ...

  2. MVC中利用ActionFilterAttribute过滤关键字

    在开发过程中,有时候会对用户输入进行过滤,以便保证平台的安全性.屏蔽的方法有很多种,但是今天我说的这种主要是利用MVC中的ActionFilterAttribute属性来实现.由于MVC天然支持AOP ...

  3. ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理

    话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐 ...

  4. mpi中利用自定义归约操作实现merge

    在归并排序中,很重要的一步是将两个排序数组合并成一个数组,这个操作叫merge.merge操作可以用来解决某些Top K问题. 问题描述 在哼唱搜索中,用户通过哼唱一个音乐片段去搜索与其相似的音乐.后 ...

  5. MVC中利用knockout.js实现动态uniqueId

    题目比较拗口,但是这篇文章确实直说这一点. knockout.js是一个JS库,它的官网是http://knockoutjs.com/ 这篇文章的重点是knockout在工作的一个功能中的应用.最终效 ...

  6. asp.net mvc 中的自定义验证(Custom Validation Attribute)

    前言

  7. asp.net mvc 5 利用ActionFilterAttribute实现权限过滤

    关于c#属性的教程:http://www.runoob.com/csharp/csharp-attribute.html 在asp.net mvc5中,可以利用ActionFilterAttribut ...

  8. 怎么在MVC中使用自定义Membership

    首先我们来看看微软自带的membership: 我们打开系统下aspnet_regsql.exe 地址一般位于: C:\WINDOWS\Microsoft.NET\Framework\v2.0.507 ...

  9. [转]怎么在MVC中使用自定义Membership

    本文转自:http://www.cnblogs.com/angelasp/p/4078244.html 首先我们来看看微软自带的membership: 我们打开系统下aspnet_regsql.exe ...

随机推荐

  1. Swift控制流

    本文简单的介绍swift一些基本语法的使用,在本文中不会做更深的剖析,只提及一些语法的简单的使用,快速学会编写swift程序.高手请绕路走嘿嘿 常量与变量: swift中定义所有的变量使用var,定义 ...

  2. UVa 100 - The 3n + 1 problem(函数循环长度)

    题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&pa ...

  3. 让div中的table居中

    div 标签上写  style="text-align:center" div中的table中写 style="margin:auto;"  <table ...

  4. Homebrew OS X 不可或缺的套件管理器

    Homebrew OS X 不可或缺的套件管理器,可以说Homebrew就是mac下的apt-get.yum. 1.安装homebrew brew的安装很简单,使用一条ruby命令即可,Mac系统上已 ...

  5. 【nginx】负载均衡和proxy的配置

    简介 使用upstream模块实现nginx负载均衡使用nginx_upstream_check_module模块实现后端服务器的健康检查使用nginx-sticky-module扩展模块实现Cook ...

  6. uva 572 oil deposits——yhx

    Oil Deposits  The GeoSurvComp geologic survey company is responsible for detecting underground oil d ...

  7. Ngrok远程桌面及ssh配置

    上一篇Ngrok 内网穿透利器 使用教程我们讲到Ngrok的基本使用教程,这篇描述一下Ngrok的远程桌面及ssh配置 Step 1 修改配置文件ngrok.cfg server_addr: &quo ...

  8. URAL 2014 Zhenya moves from parents --线段树

    题意:儿子身无分文出去玩,只带了一张他爸的信用卡,当他自己现金不足的时候就会用信用卡支付,然后儿子还会挣钱,挣到的钱都是现金,也就是说他如果有现金就会先花现金,但是有了现金他不会还信用卡的钱.他每花一 ...

  9. Spring整合Hibernate详细步骤

    阅读目录 一.概述 二.整合步骤 回到顶部 一.概述 Spring整合Hibernate有什么好处? 1.由IOC容器来管理Hibernate的SessionFactory 2.让Hibernate使 ...

  10. 数据结构Java实现06----中缀表达式转换为后缀表达式

    本文主要内容: 表达式的三种形式 中缀表达式与后缀表达式转换算法 一.表达式的三种形式: 中缀表达式:运算符放在两个运算对象中间,如:(2+1)*3.我们从小做数学题时,一直使用的就是中缀表达式. 后 ...