![](/img/trans.png)
[英]How to pass JSON string when receiving Web api method is accepting strongly typed parameter using HttpClient?
[英]How to pass Json data as parameter to web api using HttpClient
我正在使用一個asp.net應用程序,我使用HttpClient調用web api。
在Web API控制器中,我傳遞了兩個參數,一個是int,第二個是字符串。
以下是代碼:
public HttpResponseMessage Get(int submissionID, string jsonData)
{
}
當我使用httpClient傳遞一個int和一個字符串參數時,這沒有問題
下面是我的httpClient代碼:
public void GetWebApiData(int fileID, String jsonData)
{
var client = new HttpClient();
var task = client.GetAsync("http://localhost:1469/api/Smartling/" + fileID + "/"+jsonData)
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
var getVal = jsonString.Result;
});
task.Wait();
}
在上面的代碼中如果我傳遞而不是json數據它給出錯誤響應代碼400 Bad Request。
我使用jQuery ajax調用,它沒有問題。
如何將JSON數據作為參數傳遞?
說你上課了
public class Sample
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
在客戶端
public async static Task<Boolean> GetWebApiData(int fileID,string jsonData)
{
var client = new HttpClient();
Sample model = new Sample();
model = Newtonsoft.Json.JsonConvert.DeserializeObject<Sample>(jsonData);
var response = await client.GetAsync(string.Format("http://sample.com/api/test/{0}?model.value1={1}&model.value2={2}", fileID ,model.Value1, model.Value2));
if (response.StatusCode == HttpStatusCode.OK)
return true;
else
return false;
}
在服務器端
[HttpGet]
public IHttpActionResult Get(int id,[FromUri]Sample model)
{
//do something
return Ok();
}
另外請使用“string”而不是“String”類
public void GetWebApiData(int fileID,String jsonData)
如果不工作
在將數據作為參數傳遞之前,請嘗試使用stringify或SerializeObject()來轉換該數據。
像JSON.stringify(jsonData); 或者JsonConvert.SerializeObject(jsonData);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.