/// <summary>
/// SQL 注入拦截
/// </summary>
public class SqlFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
bool b = false;
try
{
if (context.HttpContext.Request.Method == "GET")
{
var arguments = context.ActionArguments;
foreach (var item in arguments)
{
if (!ProcessSqlStr(item.Value.ToString(), 1))
{
b = true;
break;
}
}
}
else if (context.HttpContext.Request.Method == "POST")
{
var arguments = context.ActionArguments;
foreach (var item in arguments)
{
if (item.Value == null)
{
continue;
}
var type = item.Value.GetType();
// 拼接在URL的 参数
if (type.FullName == "System.String")
{
if (!ProcessSqlStr(item.Value.ToString(), 1))
{
b = true;
break;
}
}
else
{
var properties = item.Value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
// 用实体参数传数的
if (properties != null && properties.Length > 0)
{
foreach (var p in properties)
{
var val = p.GetValue(item.Value, null);
if (!ProcessSqlStr(val.ToString(), 1))
{
b = true;
break;
}
}
}
else
{
// 拼接在URL的
if (!ProcessSqlStr(item.Value.ToString(), 1))
{
b = true;
break;
}
}
}
}
}
}
catch (Exception e)
{
// 错误处理: 处理用户提交信息!
Logger<SqlFilter>.Error("SQL注入拦截异常", e);
}
if (b)
{
context.Result = new JsonResult(ResultMsg<object>.GetErrorMsg("非法参数"));
}
else
{
base.OnActionExecuting(context);
}
}
////<summary>
/// 分析用户请求是否正常
///</summary>
///<param name="Str">传入用户提交数据</param>
///<returns>返回是否含有SQL注入式攻击代码</returns>
private bool ProcessSqlStr(string Str, int type)
{
string SqlStr;
if (type == 1)
SqlStr = "exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare";
else
SqlStr = "and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare";
bool ReturnValue = true;
try
{
if (Str != "")
{
Str = Str.Trim().ToLower();
string[] anySqlStr = SqlStr.Split('|');
foreach (string ss in anySqlStr)
{
if (Str.IndexOf(ss) >= 0)
{
ReturnValue = false;
}
}
}
}
catch
{
ReturnValue = false;
}
return ReturnValue;
}
配置拦截器