Pass an array of integers to ASP.NET Web API?

前端 未结 17 1731
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:40

I have an ASP.NET Web API (version 4) REST service where I need to pass an array of integers.

Here is my action method:



        
17条回答
  •  情深已故
    2020-11-22 05:06

    You may try this code for you to take comma separated values / an array of values to get back a JSON from webAPI

     public class CategoryController : ApiController
     {
         public List Get(String categoryIDs)
         {
             List categoryRepo = new List();
    
             String[] idRepo = categoryIDs.Split(',');
    
             foreach (var id in idRepo)
             {
                 categoryRepo.Add(new Category()
                 {
                     CategoryID = id,
                     CategoryName = String.Format("Category_{0}", id)
                 });
             }
             return categoryRepo;
         }
     }
    
     public class Category
     {
         public String CategoryID { get; set; }
         public String CategoryName { get; set; }
     } 
    

    Output :

    [
    {"CategoryID":"4","CategoryName":"Category_4"}, 
    {"CategoryID":"5","CategoryName":"Category_5"}, 
    {"CategoryID":"3","CategoryName":"Category_3"} 
    ]
    

提交回复
热议问题