2016-10-14 111 views
-1

我創建了一個網頁API這樣 enter image description here在網絡表單應用asp.net最好調用網頁API C#

和控制器:

public tbl_Users Get(int id) 
    { 
     DocManagerEntities1 db = new DocManagerEntities1(); 
     var data = from item in db.tbl_Users 
        where item.U_ID == id 
        select item; 
     return data.FirstOrDefault(); 
    } 

現在我想調用此API在asp.net c#webform應用程序 最好的辦法是做什麼? (我不想用jQuery做到這一點) 非常感謝

+0

然後如何調用API? –

+0

@syedmhamudulhasanakash與http客戶端通話 –

回答

0

這裏是我的API實現

模型

public class Cars 
    { 
     public string carName; 
     public string carRating; 
     public string carYear; 
    } 

我的API控制器

public class DefaultController : ApiController 
    { 
     public HttpResponseMessage GetCarses() 
     { 
      List<Cars> carList = new List<Cars>(); 
      carList.Add(new Cars 
      { 
       carName = "a", 
       carRating = "b", 
       carYear = "c" 
      }); 
      carList.Add(new Cars 
      { 
       carName = "d", 
       carRating = "e", 
       carYear = "f" 
      }); 
      return Request.CreateResponse(HttpStatusCode.OK, carList); ; 
     } 
    } 

,並從HttpClient的

我的迴應
String jsonData; 
      string url = 
       String.Format(
        @" http://localhost:37266/api/Default/GetCars"); 

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
      { 

       using (Stream stream = response.GetResponseStream()) 
       using (StreamReader reader = new StreamReader(stream)) 
       { 
        jsonData = reader.ReadToEnd(); 
       } 

       //Console.WriteLine(jsonData); 
      } 
      var cars = new JavaScriptSerializer().Deserialize<List<Cars>>(jsonData); 
      var ss = cars; 

不要忘記添加

protected void Application_Start() 
     { 
      //add this line if not 
      GlobalConfiguration.Configure(WebApiConfig.Register); 
      ... 
     }