刚刚开始学习WCF WebAPI,正准备写一些学习笔记。没想到今天去WebAPI主页发现一个醒目的提示:“Announcement: WCF Web API is now ASP.NET Web API! ASP.NET Web API released with ASP.NET MVC 4 Beta. The WCF Web API and WCF support for jQuery content on this site wll removed by the end of 2012.” 所有WebAPI相关的文档和下载都被移到了新站点:http://www.asp.net/web-api。之前单独的CHM的帮助文件下载链接找不到了,帮助文档也只有几个简单的教程。之前就感觉WebAPI和ASP.net MVC太像了:URL路由,HTTP Method特性,模型绑定等等。只是WebAPI比MVC更加轻量级,更加restful。
初略的看了一下First ASP.NET Web API的例子,新增了一个ApiController基类,只要定义继承与此类的controller,就可以直接是WebAPI了
namespace HelloWebAPI.Controllers
{
public class ProductsController : ApiController
{
// Methods not shown...
}
}
public IEnumerable<Product> GetAllProducts()
{
return new List<Product>
{
new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },
new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },
new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M }
};
}
public Product GetProductById(int id)
{
if (id < 1 || id > 3)
{
throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
}
return new Product() { Id = id, Name = "Gizmo " + id.ToString(), Price = id + 0.99M };
}