2016-07-22 106 views
1

創建一個Web API,通過該API傳遞id數組並返回OracleDB的結果。在ASP .NET Web API中傳遞參數數組

public class SampleController : ApiController 
{ 
    public string Getdetails([FromUri] int []id) 
    { 
     string inconditons = ""; 
     for (int i = 0; i < id.Length; i++) 
     { 
      if (i == id.Length - 1) 
      { 
       inconditons = inconditons + id[i]; 
      } 
      else 
      { 
       inconditons = inconditons + id[i] + ", "; 
      } 
     } 
     using (var dbConn = new OracleConnection("DATA SOURCE=X;PASSWORD=03JD;PERSIST SECURITY INFO=True;USER ID=IN")) 
     { 
      dbConn.Open(); 
      var strQuery = @"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER IN (" + inconditons + ");"; 
      var queryResult = dbConn.Query<SamModel>(strQuery); 
      return JsonConvert.SerializeObject(queryResult); 
     } 
    } 
} 

而稱爲http://localhost:35432/api/Sample?id=1&id=83它引發錯誤的API上VAR QueryResult中= dbConn.Query(strQuery)話說; enter image description here 但是,如果我只給一個參數如下它的工作原理

var strQuery = @"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER =" +id ; 

任何人都可以請建議我什麼是這裏的問題作爲一個參數的作品。謝謝

+0

按下'View Details'並展開'Internal Exception'屬性以獲得更準確的信息。 –

+0

它說{「ORA-00911:invalid character」} – trx

+1

不要使用連接字符串來執行您的查詢。使用[參數化查詢](https://blogs.msdn.microsoft.com/sqlphp/2008/09/30/how-and-why-to-use-parameterized-queries/),否則你很容易出錯這和SQL注入攻擊。 – mason

回答

1

檢查以確保您的查詢中沒有任何雜散字符。

正如評論

使用參數化查詢陳述,否則你容易受到像 這和SQL注入攻擊的錯誤。

因此,在執行時將id數組傳遞給參數化查詢。

這裏是你的例子的重構版本。

public class SampleController : ApiController { 
    public string Getdetails([FromUri] int[] id) { 
     var inconditions = id.Distinct().ToArray(); 
     using (var dbConn = new OracleConnection("DATA SOURCE=h;PASSWORD=C;PERSIST SECURITY INFO=True;USER ID=T")) { 
      dbConn.Open(); 
      var strQuery = "SELECT PRIO_CATEGORY_ID AS PRIO, LANG_ID AS LANG, REC_DATE AS REC, REC_USER AS RECUSER, DESCR, COL_DESCR AS COL, ROW_DESCR AS DROW, ABBR FROM STCD_PRIO_CATEGORY_DESCR WHERE REC_USER IN (:p)"; 
      var queryResult = dbConn.Query<SamModel>(strQuery, new { p = inconditions }); 
      return JsonConvert.SerializeObject(queryResult); 
     } 
    } 
} 
+0

感謝NKosi,問題是它說,在var queryResult = dbConn.Query (strQuery,new {p = inconditions}); – trx

+0

@trx簡單的錯字。修正了 – Nkosi

+0

在var queryResult = dbConn.Query中仍然收到相同的錯誤{「ORA-00936:missing expression」}} (strQuery,new {p = inconditions}); – trx

1

你的代碼對我來說看起來很好。如果你的id數組參數是空的,它可能會失敗(但它會是一個不同於你現在看到的錯誤)。在代碼中放置一個斷點並檢查其值。

同樣爲了將您的數組轉換爲字符串,您可以使用String.Join方法。

var ids = String.Join(",",id); 

這會給結果像"1,3,5",假設你的int數組有3項,1,3和5

現在你可以在你的查詢中使用此字符串變量。您也可以考慮將這些數據作爲參數傳遞。

var q= " ... where REC_USER IN (@ids);" //Please fill the missing part of query 
var result = con.Query<SomeModel>(q,new { ids });