本章節簡單介紹一下使用ASP.NET MVC Web API 做增刪改查。目前很多Http服務還是通過REST或者類似RESP的模型來進行數據操作的。下面我們通過創建一個簡單的Web API來管理聯系人
說明:為了方便數據不使用真正的數據庫,而是通過內存數據模擬
1. Web API中包含的方法
Action |
HTTP method |
Relative URI |
GetAllContact |
GET |
/api/contact |
GetContact |
GET |
/api/contact /id |
GetListBySex |
GET |
/api/contact?sex=sex |
PostContact |
POST |
/api/contact |
PutContact |
PUT |
/api/contact/id |
DeleteContact |
DELETE |
/api/contact/id |
http 四個主要的處理方法(get,put,post,delete)能夠用來處理匹配增刪改查操作:
Get 可以在服務端檢索匹配URI匹配的資源,不會對服務器數據進行修改操作
Put 用戶修改URI指定的特定資源,如果服務端允許,Put 也可以用戶創建新的資源
Post 可以用於創建一個資源。服務端會為這個資源創建一個新的URI,並且將這個資源作為ResposeMessage 的一部分返回
Delete 用戶刪除URI匹配的資源
2. 創建一個工程
(1) 啟動VS2012,在已經安裝的模板中選擇ASP.NET MVC4 Web 應用程序,單擊確定
(2) 在ASP.NET MVC 4 項目對話框中選擇 Web API,單擊確定
(3) 添加一個Model,工程選擇Models文件夾右鍵添加一個實體類,代碼如下
{
public int ID { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public DateTime Birthday { get; set; }
public int Age { get; set; }
}
(4) 添加一個數據操作接口
{
/// <summary>
/// 查詢所有
/// </summary>
/// <returns></returns>
IEnumerable<Contact> GetListAll();
/// <summary>
/// 根據ID查詢
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Contact GetByID( int id);
/// <summary>
/// 添加
/// </summary>
/// <param name="contact"></param>
/// <returns></returns>
Contact Add(Contact contact);
/// <summary>
/// 根據ID刪除
/// </summary>
/// <param name="id"></param>
void Remove( int id);
/// <summary>
/// 修改
/// </summary>
/// <param name="contact"></param>
/// <returns></returns>
bool Update(Contact contact);
}
(5) 添加數據操作接口實現類
{
private Log.Log log = Log.Log.Instance( typeof(ContactRep));
private List<Contact> list = new List<Contact>();
public ContactRep()
{
log.Info( " 執行構造方法 ");
list.Add( new Contact() { ID = 1, Age = 23, Birthday = Convert.ToDateTime( " 1977-05-30 "), Name = " 情緣 ", Sex = " 男 " });
list.Add( new Contact() { ID = 2, Age = 55, Birthday = Convert.ToDateTime( " 1937-05-30 "), Name = " 令狐沖 ", Sex = " 男 " });
list.Add( new Contact() { ID = 3, Age = 12, Birthday = Convert.ToDateTime( " 1987-05-30 "), Name = " 郭靖 ", Sex = " 男 " });
list.Add( new Contact() { ID = 4, Age = 18, Birthday = Convert.ToDateTime( " 1997-05-30 "), Name = " 黃蓉 ", Sex = " 女 " });
}
public IEnumerable<Contact> GetListAll()
{
return list;
}
public Contact GetByID( int id)
{
return list.Find(item => item.ID == id);
}
public Contact Add(Contact contact)
{
if (contact == null)
{
throw new NullReferenceException( " 空引用異常 ");
}
int maxid = list.Max(item => item.ID);
contact.ID = maxid + 1;
list.Add(contact);
return contact;
}
public void Remove( int id)
{
list.RemoveAll(item=>item.ID==id);
}
public bool Update(Contact contact)
{
if (contact == null)
{
throw new NullReferenceException( " 空引用異常 ");
}
Remove(contact.ID);
list.Add(contact);
return true;
}
}
(6)在Controllers文件中添加一個APIController
3. 獲得一個資源
Action |
HTTP method |
Relative URI |
GetAllContact |
GET |
/api/contact |
GetContact |
GET |
/api/contact/id |
GetListBySex |
GET |
/api/contact?sex=sex |
獲得所有聯系人
{
return provider.GetListAll();
}
這個方法以Get開頭,用於匹配Get方式請求,因為這個方法沒有參數,所以這個方法將匹配/api/contact的請求
根據id獲得聯系人
{
Contact contact = provider.GetByID(id);
if (contact == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return contact;
}
這個方法也是以Get方式開頭,而這個方法包含一個id參數,這個方法會匹配/api/contact/id 的請求,而請求中的參數id會自動轉換為int類型
如果沒有找到相應id的聯系人,則會拋出一個HttpResponseMessage的異常,這個異常是指向的404異常,請求資源不存在。
根據性別獲得資源
{
return provider.GetListAll().Where(item => item.Sex == sex);
}
如果一個請求中包含了一個查詢的參數,web api 將嘗試匹配/api/contact?sex=sex
4. 創建一個資源
客戶端發送一個Post請求,會創建一個新的contact
{
contact = provider.Add(contact);
return contact;
}
為了處理post請求,我們需要聲明一個以post開頭的方法,方法中包含一個Contact類型的參數,這個參數從請求的body中序列化而來,所以客戶端調用的時候傳遞的要是一個序列化過的Contact對象,序列化的格式可以是json,xml。
創建資源響應狀態:
Response Code: 默認情況下,web api框架設置響應的狀態為200(OK), 基於Http/1.1 協議,在使用post創建一個資源contact的時候,服務器響應狀態為201 (Created)
Location: 當創建一個新的資源之后,我們需要 Response Headers 路徑中包含一個URI。Web API框架將這個邊的非常簡單,看如下代碼:
{
contact = provider.Add(contact);
HttpResponseMessage response = Request.CreateResponse<Contact>(HttpStatusCode.Created, contact);
string uri = Url.Link( "", new { id = contact.ID });
response.Headers.Location = new Uri(uri);
return response;
}
這個方法返回的是一個HttpResponseMessage 而不是一個contact對象,我們可以獲得請求響應的詳細信息,包括狀態碼以及響應頭信息。
使用CreateResponse可以創建一個HttpResonseMessage,並且會自動將Contact對象序列化寫入響應Body中。
5. 修改一個資源
{
contact.ID = id;
bool flag = provider.Update(contact);
if (!flag)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
方式是以Put開頭,當請求Mehtod 為Put,這個請求將匹配這個方法,方法中包含了兩個參數,這兩個參數來自URI請求參數和Request Body 中
6. 刪除一個資源
{
provider.Remove(id);
throw new HttpResponseException(HttpStatusCode.NoContent);
}
刪除基本和上面都一樣了,只是請求 method 不一樣而已,這里不再累述
客戶端調用參考上一章說明代碼
相關參考文章鏈接
ASP.NET MVC Web API 學習筆記---第一個Web API程序