回到目錄
上一講中介紹了使用HttpClient如何去調用一個标準的Web Api接口,并且我們知道了Post,Put方法隻能有一個FromBody參數,再有多個參數時,上講提到,需要将它封裝成一個對象進行傳遞,而這講主要圍繞這個話題來說,接口層添加一個新類User_Info,用來進行資料傳遞,而用戶端使用網頁ajax和控制台HttpClient的方式分别進行實作,Follow me!
下面定義一個複雜類型對象
public class User_Info
{
public int Id { get; set; }
public string Name { get; set; }
public string Info { get; set; }
}
下面修改上次的api部分,讓它對這個對象進行操作
[CorsAttribute("http://localhost:3321")]
public class RegisterController : ApiController
{
public static List<User_Info> Model = new List<User_Info>()
{
new User_Info{Id=1,Name="zzl",Info="zzl是樓主"},
new User_Info{Id=2,Name="zhz",Info="zhz是zzl的兒子"},
new User_Info{Id=3,Name="zql",Info="zql是zzl的妻子"},
new User_Info{Id=4,Name="bobo",Info="bobo是zzl的朋友"}
};
// GET api/values
public IEnumerable<User_Info> Get()
{
return Model;
}
// GET api/values/5
public User_Info Get(int id)
{
var entity = Model.FirstOrDefault(i => i.Id == id);
return entity;
}
// GET api/values/5?leval=1
public HttpResponseMessage Get(int id, int leval)
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("<em style='color:red'>成功響應(id,level)</em>", System.Text.Encoding.UTF8, "text/html")
};
}
// POST api/values
public HttpResponseMessage Post([FromBody]User_Info value)
{
Model.Add(new User_Info
{
Id = value.Id,
Info = value.Info,
Name = value.Name,
});
//使用者登陸相關
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("添加資料成功,使用者ID:" + value.Id, System.Text.Encoding.UTF8, "text/plain")
};
}
// PUT api/values?userid=5
public HttpResponseMessage Put(int userid, [FromBody]User_Info value)
{
var entity = Model.FirstOrDefault(i => i.Id == userid);
entity.Info = value.Info;
entity.Name = value.Name;
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("修改資料成功,主鍵:" + userid + ",對象:" + value.Name)
};
}
// DELETE api/values/5
public HttpResponseMessage Delete(int id)
{
Model.Remove(Model.FirstOrDefault(i => i.Id == id));
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("删除資料成功")
};
}
而最關鍵的地方還是在各個用戶端調用的時候,首先,你不能指望用戶端去引用你的程式集,因為,不能平台無法實作這種引用(java & c#,js & C#,php & c#),是以,在調用時需要有它們各自的方法,而JS的ajax調用時,直接使用json對象即可,鍵名對象
實體的屬性,在使用HttpClient時,直接為FormUrlEncodedContent對象賦一個鍵值對的集合即可,下面分别介紹一下
HTML的JS實作
$.ajax({
url: "http://localhost:52824/api/register",
type: "POST",
data: { Id: 5, Name: '新來的', Info: '大家好' },//這裡鍵名稱必須為空,多個參數請傳對象,api端參數名必須為value
success: function (data) {
console.log("post:" + data);
}
});
$.ajax({
url: "http://localhost:52824/api/register",
type: "GET",
success: function (data) {
for (var i in data) {
console.log(data[i].Id + " " + data[i].Name);
}
}
});
結果截圖
Console程式中使用HttpClient對象進行實作
/// <summary>
/// HttpClient實作Post請求
/// </summary>
static async void dooPost()
{
string url = "http://localhost:52824/api/register";
//設定HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//建立HttpClient(注意傳入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{ {"Id","6"},
{"Name","添加zzl"},
{"Info", "添加動作"}//鍵名必須為空
});
//await異步等待回應
var response = await http.PostAsync(url, content);
//確定HTTP成功狀态值
response.EnsureSuccessStatusCode();
//await異步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
/// <summary>
/// HttpClient實作Get請求
/// </summary>
static async void dooGet()
{
string url = "http://localhost:52824/api/register?id=1";
//建立HttpClient(注意傳入HttpClientHandler)
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
//await異步等待回應
var response = await http.GetAsync(url);
//確定HTTP成功狀态值
response.EnsureSuccessStatusCode();
//await異步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
/// <summary>
/// HttpClient實作Put請求
/// </summary>
static async void dooPut()
{
var userId = 1;
string url = "http://localhost:52824/api/register?userid=" + userId;
//設定HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//建立HttpClient(注意傳入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"Name","修改zzl"},
{"Info", "Put修改動作"}//鍵名必須為空
});
//await異步等待回應
var response = await http.PutAsync(url, content);
//確定HTTP成功狀态值
response.EnsureSuccessStatusCode();
//await異步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
回到目錄
作者:倉儲大叔,張占嶺,
榮譽:微軟MVP
QQ:853066980
支付寶掃一掃,為大叔打賞!
