SQL 注入 处理

SqlHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public static class SqlHelper
{
    /// <summary>
    /// 替换SQL特殊字符
    /// </summary>
    /// <param name="obj">需序转化的对象</param>
    /// <returns></returns>
    public static string ToMSSQL(this String obj)
    {
        return obj.Replace("'", "''").Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]");
    }
}
View Code

 

在asp.net程序设计中,为了网页的安全我们经常要做防止SQL注入,下面的这个方法只是

        在一定程度上解决了这个问题:

        添加引用:

        using System.Text.RegularExpressions;

        方法引用

        string str=GetSafeSQL(string value);

         方法如下:

         /// <summary>
         /// 过滤SQL非法字符串
         /// </summary>
         /// <param name="value"></param>
         /// <returns></returns>
        public static string GetSafeSQL(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
            value = Regex.Replace(value, @";", string.Empty);
            value = Regex.Replace(value, @"'", string.Empty);
            value = Regex.Replace(value, @"&", string.Empty);
            value = Regex.Replace(value, @"%20", string.Empty);
            value = Regex.Replace(value, @"--", string.Empty);
            value = Regex.Replace(value, @"==", string.Empty);
            value = Regex.Replace(value, @"<", string.Empty);
            value = Regex.Replace(value, @">", string.Empty);
            value = Regex.Replace(value, @"%", string.Empty);
            return value;
        }

 

测试

create table #test1
(name varchar(200))
insert into #test1 values('sdfdsfdsf%')
insert into #test1 values('sdfdsfdsf')

select * from #test1 where name like '%[%]%'
drop table #test1

 

posted @ 2020-09-02 20:39  三瑞  阅读(145)  评论(0编辑  收藏  举报