zoukankan      html  css  js  c++  java
  • MVC中利用自定义的ModelBinder过滤关键字

    上一篇主要讲解了如何利用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了,下面开始测试:

    image

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

    image

    看来,系统会自动检测我们的输入值,发现有非法字符,会弹出错误提示,还好我们可以通过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>

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

    image

    我们可以看到,通过我们自定义的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);
            }
        }
    }
    
  • 相关阅读:
    1.两数之和 力扣,水题
    525.连续数组 力扣 (前缀和)
    [LeetCode]56. Group Anagrams变位词分组
    界面布局注意(一)
    docker常用命令
    docker常用批量操作命令
    Golang package之math/rand
    (三)虚拟机与Linux新尝试——20155306白皎
    洛谷 P1383 codevs 3333 高级打字机
    BZOJ 1013 cogs 1845 [JSOI2008]球形空间产生器sphere
  • 原文地址:https://www.cnblogs.com/scy251147/p/3687512.html
Copyright © 2011-2022 走看看