C# 使用 LINQ to SQL 是否有助于防止 SQL 注入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/473173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Will using LINQ to SQL help prevent SQL injection
提问by Bill Martin
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?
我正在建立一个公共站点,我想到的第一件事就是 SQL 注入。我有一些正在保存的文本字段,并且正在使用 linq 更新/写入数据库。我使用 linq 安全吗?
This example is creating the user account.
此示例正在创建用户帐户。
Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();
This example is changing the password
这个例子是更改密码
MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
mProfileRecord.Password = sNewPassword;
dc.SubmitChanges();
Are these safe? Does LINQ parameterize the SQL it generates automatically?
这些安全吗?LINQ 是否参数化它自动生成的 SQL?
采纳答案by Galwegian
Yes, LINQ will help stop SQL injection.
是的,LINQ 将有助于阻止 SQL 注入。
LINQ to SQL passes all data to the database via SQL parameters. So, although the SQL query is composed dynamically, the values are substitued server side through parameters safeguarding against the most common cause of SQL injection attacks.
LINQ to SQL 通过 SQL 参数将所有数据传递到数据库。因此,尽管 SQL 查询是动态组合的,但值是通过参数替换服务器端的,以防止 SQL 注入攻击的最常见原因。
Also, see Eliminate SQL Injection Attacks Painlessly with LINQfor some info.
另外,请参阅使用 LINQ 轻松消除 SQL 注入攻击以获取一些信息。
回答by Amy B
You're good to go. Linq does parameterize the data it sends to the database.
你很高兴去。Linq 确实参数化了它发送到数据库的数据。
Use the Log property to check out what's happening: dc.Log = Console.Out;
使用 Log 属性检查发生了什么: dc.Log = Console.Out;
回答by Jan Bannister
It should because the SQL emitted uses named parameters which cannot be exploited to execute arbitrary SQL.
应该是因为发出的 SQL 使用了不能被利用来执行任意 SQL 的命名参数。