因爲給予REST的Web服務很是簡單易用,它愈來愈成爲企業後端服務集成的首選方法。本文這裏介紹一下如何經過微軟的Asp.Net WebAPI快速構建REST-ful 服務。web
首先建立一個Asp.Net Web應用程序(我這裏用的是Visual Studio 2013,它已經內置了Web API2)。後端
在出來的模板中選擇Empty(空項目),並勾選WebAPI。點擊肯定後,就建立了一個空的WebAPI服務。api
此時只有一個空項目,尚未任何功能,在進行下一步以前,首先咱們來看一下REST的基本操做模型,大體能夠分爲以下四種:瀏覽器
很是經典的CRUD模型。在Web API中實現這樣一個的模型是很是簡單的,直接使用嚮導建一個Controller便可asp.net
若是用傳統的嚮導,記得把嚮導後面的那個1給去掉:spa
默認的模板內容以下:.net
public class ValuesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
} 3d
這其實已經幫咱們實現了一個最基本的服務了,不過這個服務中只實現了Get,它支持以下兩種中方式的URL訪問(其它的方式也能訪問,但沒有具體的效果): rest
按Ctrl + F5中執行,在瀏覽器中輸入相應的地址便可看到結果 blog
下面咱們要作的就是完善它,實現一個簡單的查詢功能,這裏我引用了微軟官方的一個例子:
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> Get()
{
return products;
}
public IHttpActionResult Get(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
此時,咱們就能夠在瀏覽器中看到結果了(因爲Controller更名字了,此時的地址就變成了api/products)
到此爲止,一個基於Asp.net Web API的 簡單的REST Web服務就構建完成了,因爲篇幅所限,這裏就不作更多的介紹了,跟多信息能夠參看微軟官方文檔:Getting Started with ASP.NET Web API 2。另外,若是想對REST有更深刻的瞭解的話,能夠看看infoq的這篇文章:深刻淺出REST。關於Asp.net Web API其它內容,我後續大概還會陸續寫幾篇文章來介紹它。