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格式的结果