应用程序通信一直是架构设计方面的终点,微软从DCOM到.NET Remoting,再到WCF,一致致力于提供统一,规范的通信编程模式。WCF作为重量级的通信框架,一时间成为了SOA和WebService的代名词。在非Web应用领域,WCF的地位无可撼动,SOA包括的内容很大,单纯一个WCF就代表了SOA的说法站不住脚,即使是在微软的技术体系内。进入了web时代,移动大行其道。WCF的劣势慢慢显现出来了。WCF虽然应用起来相对灵活,但是跟随微软技术潮流的开发者不难发现,ASP.NET MVC5开始支持mobile的应用,加上HTML5,Jquery,ExtJs对mobile的支持,多终端的模式下,WCF的客户端需要个性化定制开发,java的客户端如果要使用WCF的服务相对来说还是比较繁琐的。那么安卓客户端,IOS客户端呢?将来可能还有更多的终端需要支持,比如智能硬件和可穿戴设备呢?
无论是哪种通信方式,底层都使基于Http的模式,那么能不能开发一种全新的通信方式,让所有的服务消费者都能够通过统一的方式来使用服务呢?ASP.NET WebAPI就是基于这样的想法诞生的。通常认为ASP.NET WebAPI是轻量级的WCF。采用Http的GET/POST/DELETE等方式来访问,认为所有可用的服务都使资源,而不关心到底是什么类型的语言开发的,这就是REST API架构模式。
1.新建项目
新增实体类Products
namespace WebApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
新增控制器(ApiController)
Note:ApiController和MVC的controller非常像,不同之处在于继承ApiController。
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> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
新增一个页面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Product App</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/products';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});
function formatItem(item) {
return item.Name + ': $' + item.Price;
}
function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
</head>
<body>
<div>
<h2>All Products</h2>
<ul id="products" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
</body>
</html>
根据ID查询
总结:整个页面操作均使用ajax方式进行,根据返回的结果操作dom,充分利用了jqery的特性!