2013-10-10 81 views
2

我能夠在客戶端調用Web API方法,現在我想讓它在C#代碼中。在這裏,我正在寫我的jQuery代碼。調用Web API獲取使用數據參數的方法c#

$(document).ready(function() 
{ 
    $('#btnSubmit').click(function() 
    { 
      var Params = 
      { 
        AsOndate: Todate, 
        BCRefCode: 100, 
        AccID: 90000 
      }; 
      $.ajax({ 
        type: "GET", 
        url: 'http://localhost:51093/api/account/', 
        //url: 'http://192.168.0.171:51093/api/account/', 
        data: Params, 
        dataType: "json", 
        traditional: true, 
        success: ajaxSuccess, 
        error: ajaxError 
      }); 
}); 

,我調用Web API方法

public IEnumerable GetAccountListForMapping(Params param) 
    { 
     AccList _AccList = new AccList(); 
     ListParams lstParam = new ListParams(); 
     //lstParam.Add("@FromDate", Fromdate); 
     lstParam.Add("@AsOnDate", param.AsOndate); 
     lstParam.Add("@BCRefCode", param.BCRefCode); 
     lstParam.Add("@AccID", param.AccID); 
     _AccList = (AccrList)_AccList.GetAccountMappedList(lstParam); 
     return _AccList; 
    } 

這是工作中的jQuery呼叫好..以及如何編寫相同的C#代碼

這就是我想

 Params param1 = new Params(); 
     param1.AsOndate = System.DateTime.Today; 
     param1.AccID = 90000; 
     param1.BCRefCode = 100; 
     HttpClient client = new HttpClient(); 

     client.BaseAddress = new Uri("http://localhost:51093/"); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
     HttpResponseMessage response = client.GetAsync("/api/account", param1, new JsonMediaTypeFormatter()).Result; 
     if (response.IsSuccessStatusCode) 
     {..... 
     } 

回答

1

使用此方法。

string param = "AsOndate=" + System.DateTime.Today + "&AccID=" + 90000 + "&BCRefCode=" + 100; 
    HttpResponseMessage response = client.GetAsync("/api/account?" + param,HttpCompletionOption.ResponseContentRead).Result; 

謝謝。

+1

我得到的錯誤:錯誤「System.Net.Http.HttpClient.GetAsync(串的最佳重載的方法匹配, System.Net.Http.HttpCompletionOption)'有一些無效的參數 –

+1

現在好了。它發射正確的方法並返回一些「響應」。我們如何反序列化這個迴應? –

-1

與@felix

給出的答案繼續爲你沒有改變參數的API代碼它一定會得到錯誤:

public IEnumerable GetAccountListForMapping(string param) 
    { 
     // Your Code 
    } 

,現在從「PARAM提取數據'串。

我希望這會起作用。

+2

omggggggg你再次正確回答非常感謝幫助 – Neel

2

得到的答案和它的工作對我來說

protected void btnGetdata_Click(object sender, EventArgs e) 
    { 
     HttpClient client = new HttpClient(); 
     client.BaseAddress = new Uri("http://localhost:xxxx/"); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
     string param = "AsOnDate=" + System.DateTime.Today + "&AccID=" + 90000 + "&BCRefCode=" + 100; 
     HttpResponseMessage response = client.GetAsync("/api/account?" + param, HttpCompletionOption.ResponseContentRead).Result; 
     if (response.IsSuccessStatusCode) 
     { 
      var aa = response.Content.ReadAsAsync<object>().Result; 
      object obj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YourClassName>>(aa.ToString()); 
     } 
    } 

感謝所有

相關問題