2017-05-05 80 views
0

在Swagger中插入一些值,我想將包含這些值的字符串數組傳遞給Linq。 (在這種情況下,ID是字符串)。如果我傳遞一個簡單的字符串,而不是一個數組,它可以插入一個值。但我需要傳遞一組值。C# - Swagger插入值並將字符串數組傳遞給Linq顯示NULL而不是插入的值

這裏是由試圖插入2個值當API建立了一個鏈接(它看起來怪異的數組):http://localhost:port/api/Members?ids=97882831302&ids=97882831308

的問題是,該陣列顯示NULL,而不是插入的值。我得到以下錯誤:

"ExceptionMessage": "Unable to create a null constant value of type 'System.String[]'. Only entity types, enumeration types or primitive types are supported in this context."

enter image description here

public class MembersController : ApiController 
    { 
    public HttpResponseMessage GetAllMembersByIdentifiers(string[] ids) { 
       using (sampleEntities entities = new sampleEntities()){ 
        var numbers = entities.tblmembers 
         .Where(p => ids.Contains(p.identify) ).ToList(); 

        if (numbers != null) 
        { 
         return Request.CreateResponse(HttpStatusCode.OK, numbers); 
        } 
        else 
        { 
         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Member with id: " + ids + " not found"); 
        } 
       } 
      } 
} 

回答

0

Ø認爲你已經在你的代碼2個問題..

FIRST:

用,像通數據:

98989794, //<--- 
4343545345 

第二:

在C#

我可以建議您檢查字符串null或空,如:

public class MembersController : ApiController 
     { 

     [HttpGet] 
     [Route("api/Members/Find/{ids}")] 
     public HttpResponseMessage FindMemebers([FromUri]string[] ids) { 


    // CHECK THE ARRAY NOT EMPTY 
     if(!ids.Any() || ids.All(xx=> string.isNullOrEmpty(xx)) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "empty params"); 

        using (sampleEntities entities = new sampleEntities()){ 
         var numbers = entities.tblmembers 
          .Where(p => ids.Contains(p.identify) ).ToList(); 

         if (numbers != null) 
         { 
          return Request.CreateResponse(HttpStatusCode.OK, numbers); 
         } 
         else 
         { 
          return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Member with id: " + ids + " not found"); 
         } 
        } 
       } 
    } 
+0

似乎有一個「),」缺少在首屆「如果」行。它也說「BadRequest()」不起作用(它說它不能轉換成HttpResponse)。我用「CreateErrorResponse」取代了它。我也嘗試在Swagger中用逗號「,」插入值(沒有在Swagger中說插入每行的值 - 沒有提及逗號)。我仍然收到一個錯誤:「ExceptionMessage」:「值不能爲空。\ r \ nParameter name:source」, 「ExceptionType」:「System.ArgumentNullException」' – adlisval

+0

對不起......只是嘗試調用你的方法GET (或者放一個[Route]裝飾)和[HttpGet]動詞裝飾)...並嘗試設置([FromUri] string [] ids)因爲我認爲它現在是QUERYSTRING PARAMS的方面 –

+0

可以請你分享代碼怎麼做?我試過'[Route] [HttpGet] public HttpResponseMessage GetAllMembersByIdentifiers(string [] ids){...'。 'BadRequest()'仍然用紅色加下劃線。我不知道你的意思是什麼「調用你的方法GET」...如果它重新命名爲GET,我嘗試和'BadRequest()'仍然加下劃線。 – adlisval

-1

什麼解決的是:

  1. 加入[FromUri]通過@ federico-暗示scamuzzi

  2. string[]替換爲List<string>

所以在代碼如下所示:

public HttpResponseMessage FindMemebers([FromUri]List<string> ids) { ...