当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net MVC利用自定义ModelBinder过滤关键字的方法(附demo源码下载)

asp.net MVC利用自定义ModelBinder过滤关键字的方法(附demo源码下载)

2017年12月12日  | 移动技术网IT编程  | 我要评论
本文实例讲述了mvc利用自定义modelbinder过滤关键字的方法。分享给大家供大家参考,具体如下: 前面一篇主要讲解了如何利用actionfilter过滤关键字,这篇

本文实例讲述了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("<", "<").replace(">", ">");
           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程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网