1. 程式人生 > 其它 >asp.net web api客戶端呼叫

asp.net web api客戶端呼叫

服務介面

介面1:

//Post:http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest1
[HttpPost]
public HttpResponseMessage FunctionTest1(Model1 model)
{
  ......          
}

介面2:

//Post:http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest2
[HttpPost]
public HttpResponseMessage FunctionTest2(Model2 model)
{
  ......          
}

介面引數:

public class Model1
{
public List<Model2> List1 { get; set; }
public string Name { get; set; }
}

public class Model2
{
public string Field21{get;set;}
public string Field22{get;set;}
}

客戶端呼叫

對於介面1:採用StringContent,將所傳資料序列化後寫入請求訊息體中。

var m1 = new { List1 = new List<object> { new { Field21 = "Field21", Field22 = "Field21" }, new { Field21 = "Field21", Field22 = "Field21" } }, Name = "Tests" };
HttpContent content = new StringContent(JsonConvert.SerializeObject(m1));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
HttpClient client = new HttpClient();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, @"http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest1"))
{
  request.Content = content;
  HttpResponseMessage response = client.SendAsync(request).Result;
  var r = response.Content.ReadAsAsync<object>();
  r.Wait();
  var s = r.Result.ToString();
}

如若採用FormUrlEncodedContent則無法成功。

呼叫介面2傳參的方式有兩種

第一種方法:採用FormUrlEncodedContent將請求輸入寫入訊息體中

HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>()       
{   
  {"Field21","Field21"},
  {"Field22","Field22"}
});
HttpClient client = new HttpClient();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, @"http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest2"))
{
  request.Content = content;
  HttpResponseMessage response = client.SendAsync(request).Result;
  var r = response.Content.ReadAsAsync<object>();
  r.Wait();
}

第二種方法:採用StringContent將請求資料寫入訊息體中

var model = new { Field21 = "Field21", Field22 = "Field22" };
HttpContent content = new StringContent(JsonConvert.SerializeObject(model));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, @"http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest2"))
{
  request.Content = content;
  HttpResponseMessage response = client.SendAsync(request).Result;
  var r = response.Content.ReadAsAsync<object>();
  r.Wait();
}