如果字符串是在 C# 中插入的,如何检查接受字符串的方法内部?
How is it possible to check inside a method which accepts a String if the string was interpolated in C#?
如果字符串是在 C# 中插入的,如何检查接受字符串的方法内部?
我看到 EF 可以做到这一点 here。
// String interpolation
var author = db.Authors.FromSql($"SELECT * From Authors Where AuthorId = {id}").FirstOrDefault();
Entity Framework Core will only parameterize interpolated strings if they are supplied inline to the FromSql method call. Interpolated strings declared outside of the FromSql method call will not be parsed for parameter placeholders. In effect, you will be passing a concatenated string directly to the database, which is a SQL injection risk.
The following example is dangerous and should not be used:
var sql = $"SELECT * From Authors Where AuthorId = {id}";
var author = db.Authors.FromSql(sql).FirstOrDefault();
在阅读上面的摘录之前,我认为在一个方法中我得到了一个字符串并且不可能知道它是如何构造的。摘录让我相信这是有可能的。
内插字符串文字可以具有 string
或 FormattableString
类型,这是由类型推断确定的。
EF 使用 FormattableString
作为 FromSql
的参数类型,这样它既可以使用 Format
属性 获得格式,也可以使用 属性 获得参数GetArguments
和 GetArgument
方法。
下面是一些演示此 class 基本用法的代码。
var arg1 = 10;
var arg2 = 20;
FormattableString fs = $"Arg1 is {arg1} and Arg2 is {arg2}.";
Console.WriteLine(fs.Format);
Console.WriteLine(fs.GetArgument(0));
Console.WriteLine(fs.GetArgument(1));
// output:
Arg1 is {0} and Arg2 is {1}.
10
20
所以本质上,FormttableString
允许 EF 防止 SQL 注入,因为它 "doesn't format the string immediately",而是将格式字符串包装到一个漂亮的小对象中供 EF 操作。
如果字符串是在 C# 中插入的,如何检查接受字符串的方法内部?
我看到 EF 可以做到这一点 here。
// String interpolation
var author = db.Authors.FromSql($"SELECT * From Authors Where AuthorId = {id}").FirstOrDefault();
Entity Framework Core will only parameterize interpolated strings if they are supplied inline to the FromSql method call. Interpolated strings declared outside of the FromSql method call will not be parsed for parameter placeholders. In effect, you will be passing a concatenated string directly to the database, which is a SQL injection risk.
The following example is dangerous and should not be used:
var sql = $"SELECT * From Authors Where AuthorId = {id}";
var author = db.Authors.FromSql(sql).FirstOrDefault();
在阅读上面的摘录之前,我认为在一个方法中我得到了一个字符串并且不可能知道它是如何构造的。摘录让我相信这是有可能的。
内插字符串文字可以具有 string
或 FormattableString
类型,这是由类型推断确定的。
EF 使用 FormattableString
作为 FromSql
的参数类型,这样它既可以使用 Format
属性 获得格式,也可以使用 属性 获得参数GetArguments
和 GetArgument
方法。
下面是一些演示此 class 基本用法的代码。
var arg1 = 10;
var arg2 = 20;
FormattableString fs = $"Arg1 is {arg1} and Arg2 is {arg2}.";
Console.WriteLine(fs.Format);
Console.WriteLine(fs.GetArgument(0));
Console.WriteLine(fs.GetArgument(1));
// output:
Arg1 is {0} and Arg2 is {1}.
10
20
所以本质上,FormttableString
允许 EF 防止 SQL 注入,因为它 "doesn't format the string immediately",而是将格式字符串包装到一个漂亮的小对象中供 EF 操作。