Pages

Web API Client example

Jun 17, 2014

本文說明在 VS2013 建立一個 ASP.NET Web API 後, 先使用 Fiddler 測試 Web API 是否正常,再以 C# 撰寫用戶端程式。

建立 Web API

首先以 Visual Studio 2013 建立一個模擬 Customer 類別 CRUD 的 Web API,部分程式如下

public class CustomerController : ApiController
{
public static List ALL_Customer = null;
public CustomerController()
{
if (ALL_Customer == null)
{
ALL_Customer = new List();
ALL_Customer.Add(new Customer() { Id = 0, CustName = "TEST.com" });
}
}


// GET api/
//http://localhost:2684/Api/Customer/
public IEnumerable Get()
{
return ALL_Customer;
}

//GET api//5
//http://localhost:2684/Api/Customer/5
public Customer Get(int id)
{
return ALL_Customer.FirstOrDefault(c => c.Id == id);
}

// POST api/
public int Post([FromBody]Customer value)
{
int newId=ALL_Customer.Count+1;
ALL_Customer.Add(new Customer() { Id = newId, CustName = value.CustName });
return newId;
}

// PUT api//5
public bool Put(int id, Customer value)
{
Customer customer = ALL_Customer.FirstOrDefault(c => c.Id == id);
if (customer == null)
return false;
customer.CustName = value.CustName;
return true;
}

// DELETE api//5
public bool Delete(int id)
{
Customer customer = ALL_Customer.FirstOrDefault(c => c.Id == id);
if (customer == null)
return false;
ALL_Customer.Remove(customer);
return true;
}

public void Delete()
{
ALL_Customer.RemoveAll(r=>r.Id>=0);
}
}

 


使用 Fiddler 測試


開啟 Fiddler,點擊 [Composer]


 image


(1), (2) 選擇 Method 與 API 的網址


(3) 須加入 Content-Type: application/json


(4) 傳遞參數採用 Json 文字格式,本案例中 POST 與 PUT 需要傳入此參數。


按下 [Execute],可以查詢回傳結果


image


 


.NET Framework 4.5 以上應用程式


用戶端是 .NET Framework 4.5 以上的應用程式,建議先安裝套件 Microsoft ASP.NET Web API 2.1 Client Libraries, 有提供各種方法 GET, POST, PUT,  DELETE 非同步並直接轉換 Json 。例如:

public int NewCustomer(string custName)
{
Customer customer = new Customer() { CustName = custName };
using (var client = GetHttpClient())
{
var result = client.PostAsJsonAsync(api_URL, customer).Result;
try
{
result.EnsureSuccessStatusCode();
return result.Content.ReadAsAsync().Result;
}
catch
{
return -1;
}
}
}

 


.NET Framework 4.0 應用程式


用戶端是.NET Framework 4.0 的應用程式, 建議先安裝套件 Microsoft HTTP Client Libraries,有提供各種方法 GET, POST, PUT,  DELETE 非同步呼叫 Web API,不過針對物件與 Json 間序列化與反序列化, 需要自行處理。例如:

public int NewCustomer(string custName)
{
Customer customer = new Customer() { CustName = custName };
StringContent sendingData = JsonUtil.ObjectToStringContent(customer);
using (var client = GetHttpClient())
{
var result = client.PostAsync(api_URL, sendingData).Result;
try
{
result.EnsureSuccessStatusCode();
string readResult = result.Content.ReadAsStringAsync().Result;
return JsonUtil.StringToObject(readResult);
}
catch(Exception ex)
{
return -1;
}
}
}

完整範例 Github https://github.com/robinli/WebApiClient_Example