1:Form提交模式
在使用Form提交时,MVC框架提供了一个默认的机制。如果数据中含有恶意字,则会自动转向出错页面。
 
2:Ajax+JSON提交模式。
MVC框架未提供对于Json数据的AntiXSS支持,所以必须自行实现。
 
Step1:定义一个Attribute[AllowHtml],如果有这个标记,则说明该属性允许Html,不需要验证。
    /// <summary>
    /// 用于标记某个属性是否允许html字符
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class AllowHtmlAttribute : Attribute
    {
 
    }
 
Step2:元数据解析的时候,动态设定标记为AllowHtml的属性不激发验证。
    public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
 
        public CustomModelMetadataProvider()
        {
        }
 
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
                                                        Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            if (containerType == null || propertyName == null)
                return metadata;
 
            foreach (Attribute attr in attributes)
            {
                if (attr is AllowHtmlAttribute)
                {
                    metadata.RequestValidationEnabled = false;
                    break;
                }
            }
        }
    }
 
Step3:实现自定义ModerBinder,拦截所有的json数据,进行anti-xss验证。
/// <summary>
    /// 检测Json数据中含有恶意字符,抛出HttpRequestValidationException
    /// </summary>
    public class AntiXssModelBinder : DefaultModelBinder
    {
        protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
        {
            if (controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            {
                int index;
 
                if (controllerContext.Controller.ValidateRequest
                    && bindingContext.PropertyMetadata[propertyDescriptor.Name].RequestValidationEnabled)
                {
                    if (value is string)
                    {
                        if (AntiXssStringHelper.IsDangerousString(value.ToString(), out index))
                        {
                            throw new HttpRequestValidationException("Dangerous Input Detected");
                        }
                    }
                    else if (value is IEnumerable)
                    {
                        // 字符串数组或者集合,或者Dictionary<string, string>
                        // Dictionary的Key, Value会ToString后一起验证
                        foreach (object obj in value as IEnumerable)
                        {
                            if (obj != null)
                            {
                                if (AntiXssStringHelper.IsDangerousString(obj.ToString(), out index))
                                {
                                    throw new HttpRequestValidationException("Dangerous Input Detected");
                                }
                            }
                        }
                    }
                }
            }
 
            return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
        }
    }
 
    /// <summary>
    /// 检测绑定的单值字符串是否包含恶意字符
    /// </summary>
    public class AntiXssRawModelBinder : StringTrimModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = base.BindModel(controllerContext, bindingContext);
            if (value is string)
            {
                var result = (value as string).Trim();
                int index;
                if (AntiXssStringHelper.IsDangerousString(value.ToString(), out index))
                {
                    throw new HttpRequestValidationException("Dangerous Input Detected");
                }
            }
 
            return value;
        }
    }
}
 
Step4:在Web站点启动的时候,配置MVC框架
            RouteTableRegister.RegisterRoutes(_routes);
 
            BundleConfig.RegisterBundles(BundleTable.Bundles);
 
            ModelMetadataProviders.Current = new CustomModelMetadataProvider();
            ModelBinders.Binders.DefaultBinder = new AntiXssModelBinder();
 
举例:
     [Required]
     [AllowHtml]
     public string UserName{get;set;}
     [Required]
     public string Password{get;set;}
     注意:这时通过JSON传过来的数据Password就会报错,而UserName则不会。
 
如果Ajax传入的JSON是封装好的对象,最好也要经过封装,以下为例:
     public ActionResult Login(LoginModel model,[ModelBinder(typeof(AntiXssRawModelBinder))])
     {
     }
 
 
    //AntiXssRawModelBinder核心代码
    /// <summary>
    /// 检测绑定的单值字符串是否包含恶意字符
    /// </summary>
    public class AntiXssRawModelBinder : StringTrimModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = base.BindModel(controllerContext, bindingContext);
            if (value is string)
            {
                var result = (value as string).Trim();
                int index;
                if (AntiXssStringHelper.IsDangerousString(value.ToString(), out index))
                {
                    throw new HttpRequestValidationException("Dangerous Input Detected");
                }
            }
 
            return value;
        }
    }
     
 
如果某些参数需要支持部分HTML代码,可以采取先将该参数设置为[AllowHTML],值传到Action时,再进行手动过滤,或者 使用AntiXSS库进行编码(微软提供的AntiXSSLibrary类库)。
 
整理网络文章,如有错误,敬请指正,非常感谢!

ASP.NET MVC Anti-XSS方案的更多相关文章

  1. ASP.NET MVC 多语言方案

    前言: 好多年没写文章了,工作很忙,天天加班, 每天都相信不用多久,就会升职加薪,当上总经理,出任CEO,迎娶白富美,走上人生巅峰,想想还有点小激动~~~~ 直到后来发生了邮箱事件,我竟然忘了给邮箱密 ...

  2. 全面解析ASP.NET MVC模块化架构方案

    什么叫架构?揭开架构神秘的面纱,无非就是:分层+模块化.任意复杂的架构,你也会发现架构师也就做了这两件事. 本文将会全面的介绍我们团队在模块化设计方面取得的经验.之所以加了“全面”二字,是因为本文的内 ...

  3. asp.net MVC 3多语言方案--再次写, 配源码

    之前写了一篇asp.net MVC多语言方案,那次其实是为American Express银行开发的.有许多都是刚开始接触,对其也不太熟悉.现在再回过头去看,自己做一个小网站,完全用asp.net m ...

  4. ASP.NET安全[开发ASP.NET MVC应用程序时值得注意的安全问题](转)

    概述 安全在web领域是一个永远都不会过时的话题,今天我们就来看一看一些在开发ASP.NET MVC应用程序时一些值得我们注意的安全问题.本篇主要包括以下几个内容 : 认证 授权 XSS跨站脚本攻击 ...

  5. (转)asp.net mvc 开发环境下需要注意的安全问题(一)

    概述 安全在web领域是一个永远都不会过时的话题,今天我们就来看一看一些在开发ASP.NET MVC应用程序时一些值得我们注意的安全问题.本篇主要包括以下几个内容 : 认证 授权 XSS跨站脚本攻击 ...

  6. 深入理解ASP.NET MVC(2)

    系列目录 请求是如何进入MVC框架的(inbound) 当一个URL请求到来时,系统调用一个注册的IHttpModules:UrlRoutingModule,它将完成如下工作: 一.在RouteTab ...

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

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

  8. ASP.NET MVC异常处理方案

    异常处理是每一个系统都必须要有的功能,尤其对于Web系统而言,简单.统一的异常处理模式尤为重要,当打算使用ASP.NET MVC来做项目时,第一个数据录入页面就遇到了这个问题. 在之前的ASP.NET ...

  9. 微冷的雨ASP.NET MVC之葵花宝典(MVC)

    微冷的雨ASP.NET MVC之葵花宝典 By:微冷的雨 第一章 ASP.NET MVC的请求和处理机制. 在MVC中: 01.所有的请求都要归结到控制器(Controller)上. 02.约定优于配 ...

  10. [转]ASP.NET MVC 4 最佳实践宝典

    原文:http://www.cnblogs.com/sonykings/archive/2013/05/30/3107531.html ASP.NET MVC最佳实践 本文档提供了一套旨在帮助创建最佳 ...

随机推荐

  1. In-Memory:在内存中创建临时表和表变量

    在Disk-Base数据库中,由于临时表和表变量的数据存储在tempdb中,如果系统频繁地创建和更新临时表和表变量,大量的IO操作集中在tempdb中,tempdb很可能成为系统性能的瓶颈.在SQL ...

  2. 初识Hadoop、Hive

    2016.10.13 20:28 很久没有写随笔了,自打小宝出生后就没有写过新的文章.数次来到博客园,想开始新的学习历程,总是被各种琐事中断.一方面确实是最近的项目工作比较忙,各个集群频繁地上线加多版 ...

  3. ABP文档 - 嵌入的资源文件

    文档目录 本节内容: 简介 创建嵌入的文件 暴露嵌入的文件 使用嵌入的文件 简介 一个web应用里,客户端包含javascript,css,xml等文件,这此文件被添加到一个web项目后,发布成独立的 ...

  4. OpenSceneGraph in ActiveX by ActiveQt

    OpenSceneGraph in ActiveX by ActiveQt eryar@163.com Abstract. Qt’s ActiveX and COM support allows Qt ...

  5. MySQL 系列(一) 生产标准线上环境安装配置案例及棘手问题解决

    一.简介 MySQL是最流行的开放源码SQL数据库管理系统,它是由MySQL AB公司开发.发布并支持的.有以下特点: MySQL是一种数据库管理系统. MySQL是一种关联数据库管理系统. MySQ ...

  6. obj.style.z-index的正确写法

    obj.style.z-index的正确写法 今天发现obj.style.z-index在js里面报错,后来才知道在js里应该把含"-"的字符写成驼峰式,例如obj.style.z ...

  7. 【工具使用】mac电脑使用技巧

    本文地址 分享提纲: 1.  mac命令行和finder的交互 2. 一些mac的插件 3. 一些开发的配置 1.mac命令行和findder交互           1)命令行中打开当前文件夹: o ...

  8. PHP设计模式(三)抽象工厂模式(Abstract Factory For PHP)

    一.什么是抽象工厂模式 抽象工厂模式的用意为:给客户端提供一个接口,可以创建多个产品族中的产品对象 ,而且使用抽象工厂模式还要满足以下条件: 系统中有多个产品族,而系统一次只可能消费其中一族产品. 同 ...

  9. Java虚拟机 JVM

    finalize();(不建议使用,代价高,不确定性大) 如果你在一个类中覆写了finalize()方法, 那么你可以在第一次被GC的时候,挽救一个你想挽救的对象,让其不被回收,但只能挽救一次. GC ...

  10. ubuntu安装ANSYS17.2全过程

    本次介绍在Ubuntu kylin1604下安装Ansys 17.2的全部过程. 1 安装文件准备 关于ANSYS的软件安装文件,在网络上可以找到.这里采用SSQ版本的安装文件,如图所示,包含一个名为 ...