gpt4 book ai didi

entity-framework - Entity Framework 和原始字符串查询 - SQL 注入(inject)预防

转载 作者:行者123 更新时间:2023-12-04 07:25:39 24 4
gpt4 key购买 nike

我使用 EF 4 执行字符串查询:

string query = "SELECT * FROM Table WHERE ....";

[+ build WHERE clausule based on the user's input values]

db.ExecuteStoreQuery<TAble>(query).ToList();

我想知道如何在 taht WHERE 子句中防止该查询被 SQL 注入(inject)。有什么想法吗?

最佳答案

您需要使用参数化查询:

// Build where clause
var filters = new StringBuilder();
var parameters = new List<object>();
if (!string.IsNullOrEmpty(name))
{
if (filters.Length > 0)
filters.Append(" AND ");
filters.Append("name = @name");
var param = new SqlParameter("@name", SqlDbType.NVarChar);
param.Value = name;
parameters.Add(param);
}
...


// Build query
string query = "SELECT * FROM Table";
if (filters.Length > 0)
query = query + " WHERE " + filters;

// Execute
db.ExecuteStoreQuery<TAble>(query, parameters.ToArray()).ToList();

关于entity-framework - Entity Framework 和原始字符串查询 - SQL 注入(inject)预防,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9297903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com