標籤:des style blog http io ar color os sp
Web API一種REST架構風格的Web服務。所謂的REST架構與技術無關,而是面向資源的一種軟體架構設計。
WCF自3.5之後也提供了對REST風格的支援,但和WebAPI來比較顯得較為笨重,WebAPI提供了更輕量級的通訊架構。
我們看如何建立一個WebAPI服務
首先建立一個solution,並在該solution下面建立一個WebApi Project,
在建立的WebAPI項目中,新加Controller(類似於MVC的建立),我們起名叫CustomerController,在CustomerController中我們提供對Customer資料
簡單的添加和查詢功能。具體的需要調用倉儲來實現內部邏輯處理,倉儲類代碼如下
//Model類
namespace CustomerService.Models{ public class Customer { public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } }}
namespace CustomerService.Repository{ public interface ICustomerRepository { Customer GetCustomer(int id); int Add(Customer customer); }}
namespace CustomerService.Repository{ public class CustomerRepository : ICustomerRepository { private static List<Customer> customers = new List<Customer>() { new Customer() { ID = 1, Name = "zhangsan", Email = "zhangsan@dx.com" }, new Customer() { ID = 2, Name = "lisi", Email = "lisi@dx.com" }, new Customer() { ID = 3, Name = "wangwu", Email = "wangwu@dx.com" } }; public Customer GetCustomer(int id) { return customers.FirstOrDefault(c => c.ID == id); } public int Add(Customer customer) { int maxId = 0; if (customers != null) { maxId = customers.Max(c => c.ID); customer.ID = maxId; customers.Add(customer); } return maxId; } }}
下面就來看一下Controller的代碼
namespace CustomerService.Controllers{ public class CustomerController : ApiController { private ICustomerRepository customerRepository; public CustomerController() { customerRepository = new CustomerRepository(); } public Customer GetCustomerById(int id) { return customerRepository.GetCustomer(id); } public int AddCustomer(Customer customer) { return customerRepository.Add(customer); } }}
以上是對Web API服務的建立步驟。WebAPI中也存在路由配置,可以對服務的地址進行個人化。具體是在項目中自動產生的App_Start檔案加下WebApiConfig.cs中配置,代碼如下
namespace CustomerService{ public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "GetCustomer", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "AddCustomer", routeTemplate: "api/{controller}/add", defaults: new { id = RouteParameter.Optional } ); } }}
上面的代碼是在Application_Start()方法中調用的(建立WebAPI項目的時候自動產生好的)
namespace CustomerService{ public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } }}
至此,我們的第一個WebAPI服務已經建立成功,啟動運行該項目後(服務已啟動狀態),在瀏覽器(Chrom)中輸入服務的地址查詢單個Customer
http://localhost:24434/api/customer/1 瀏覽器會展示出Xml格式的結果
Asp.Net WebApi服務的建立