增加RunRaw方法执行原始sql语句,该方法存在sql注入风险

This commit is contained in:
falcon 2021-05-27 12:02:18 +08:00
parent 94737d4817
commit 168973791d
2 changed files with 43 additions and 0 deletions

View File

@ -26,5 +26,13 @@ namespace Falcon.StoredProcedureRunner
/// <param name="data">执行参数</param>
/// <returns>查询结果枚举</returns>
IEnumerable<object> Run(DbContext db,Type prarmType,Type returnType ,object data) ;
/// <summary>
/// 存在sql注入风险执行Sql语句并将数据库返回结果以json数据对象返回。
/// </summary>
/// <param name="db">数据上下文</param>
/// <param name="sql">要执行的sql语句</param>
/// <returns>数据库返回值json格式</returns>
string RunRaw(DbContext db,string sql);
}
}

View File

@ -4,6 +4,7 @@ using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
@ -72,8 +73,42 @@ namespace Falcon.StoredProcedureRunner
return result;
}
}
/// <summary>
/// 存在sql注入风险执行Sql语句并将数据库返回结果以json数据对象返回。
/// </summary>
/// <param name="db">数据上下文</param>
/// <param name="sql">要执行的sql语句</param>
/// <returns>数据库返回值json格式</returns>
public string RunRaw(DbContext db,string sql) {
var connection = db.Database.GetDbConnection();
using(var cmd = connection.CreateCommand()) {
cmd.CommandText = sql;
cmd.CommandType = System.Data.CommandType.Text;
connection.Open();
var dr = cmd.ExecuteReader();
var result = new StringBuilder();
if(!dr.CanGetColumnSchema())
return "";
while(dr.Read()) {
var item = new StringBuilder();
var columnSchema = dr.GetColumnSchema();
for(var i = 0;i < columnSchema.Count;i++) {
var name = dr.GetName(i);
var value = dr.IsDBNull(i) ? null : dr.GetValue(i);
item.Append($"\"{name}\":\"{value}\",");
}
result.Append($"{{{item.ToString().TrimEnd(',')}}},");
}
connection.Close();
return "[" + result.ToString().TrimEnd(',') + "]";
}
}
}
/// <summary>
/// 内部保护方法
/// </summary>
public partial class Runner
{
/// <summary>