2011-09-19 75 views

回答

1

如果你想建立你自己的提供者,你必須知道它並不那麼容易。考慮像嵌套選擇,嵌套在哪裏,等等。關於這個話題有很大的blog posts

但是你有興趣保護你的數據庫免受SQL注入攻擊。所以,如果你看看這個pageVisitConstant方法的示例代碼,那就是你運行值類型常量(string,int等)或IQueryable的地方。

針對SQL注入的保護並不複雜,您只需創建新的SQLParameter或者您可以調用方法DbProviderFactory.CreateParameter來描述here。在遍歷表達式樹時,您將需要一些集合來存儲參數。因此,修改後的代碼如下所示:

protected override Expression VisitConstant(ConstantExpression c) { 
    IQueryable q = c.Value as IQueryable; 
    if (q != null) { 
     // assume constant nodes w/ IQueryables are table references 
     sb.Append("SELECT * FROM "); 
     sb.Append(q.ElementType.Name); 
    } 
    else if (c.Value == null) { 
     sb.Append("NULL"); 
    } 
    else { 
     switch (Type.GetTypeCode(c.Value.GetType())) { 
      case TypeCode.Boolean: 
       param = dbProvider.CreateParameter(); 
       param.Name = "@param" + paramsList.Count; 
       param.Value = (((bool)c.Value) ? 1 : 0; 
       paramsList.Add(param); 
       sb.Append(param.Name); 
       break; 
      case TypeCode.String: 
       param = dbProvider.CreateParameter(); 
       param.Name = "@param" + paramsList.Count; 
       param.Value = c.Value; // you don't have to care about escaping or formatting 
       paramsList.Add(param); 
       sb.Append(param.Name); 
       break; 
      ... 
      case TypeCode.Object: 
       throw new NotSupportedException(string.Format("The constant for '{0}' is not supported", c.Value)); 
      default: 
       sb.Append(c.Value); 
       break; 
     } 
    } 
    return c; 
} 

所以當你travesing表達式樹,你正在構建的SQL字符串和收集的SQL參數。

+0

謝謝,這是一個相當的代碼片段。我認爲你有這方面的一些經驗。 –

+0

我試圖創建自己的LINQ提供程序,但任務非常困難......並且還有其他項目需要使用;) –

2

從博客post看起來像IQ工具包(或工具包的初始版本)不適合SQL注入攻擊。但是您可以自己驗證它 - 執行查詢,捕獲生成的SQL並查看是否有使用的參數。

+0

感謝您的迴應,但如果您能夠展示如何使用LINQ提供程序的參數來防止SQL注入,這將有所幫助。 –