2015-04-23 75 views
1

我有一個的WebAPI獲取方法如下圖所示如何將JSON字符串從ASP.Net傳遞給WebAPI獲取方法?

// GET api/Employee/5 
public tblEmployee GettblEmployee(int id) 
{ 
    tblEmployee tblemployee = db.tblEmployees.Find(id); 
    if (tblemployee == null) 
    { 
     throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); 
    } 

    return tblemployee; 
} 

,我想提醒的是ASP.NET網絡應用程序了

HttpClient hc; 
hc = new HttpClient(); 
string uriStr = "http://localhost/api/Employee/"; 

HttpResponseMessage response = hc.GetAsync(uriStr + "2").Result; 

var obj = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result); 

ViewBag.Message = obj.ToString(); 
return View(); 

現在我想從ASP網站通過JSON來的WebAPI,有人可以幫助我。我用Google搜索了很多,但我只能找到從JQuery的

調用

回答

0

你可以做一個使用PostAsJsonAsync

using (HttpClient hc = new HttpClient()) 
      { 
       var myModel = new Model() 
       { 
       prop1 = "prop1", prop2 = 1, prop3 = "prop3" 
       }; 
       HttpResponseMessage response = await client.PostAsJsonAsync("api/Employee/", myModel); 
       if (response.IsSuccessStatusCode) 
       { 

       } 
      } 

Example

+0

喜沙,,我想基本上通過從ASP.Net一個JSON來的WebAPI。我的WebAPI將返回一個JSON,我需要從ASP.Net接收。你能幫我兩種方法..是在WebAPI中的某種自定義POST/GET方法嗎? – SSK

+0

所以你可以使用上面的代碼,'PostAsJsonAsync'用於發佈json數據,告訴我一件事情** api/Employee/**接受什麼作爲參數?它是一些模式或字符串JSON? –

+0

現在它只是一個字符串,我希望它接受一個JSON並返回一個JSON,那麼在那個方法中會出現什麼 string strOutput ='some json string' HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, strOutput); 返回響應; – SSK

相關問題