这篇来讲讲WebApi的自托管,WebApi可以托管到控制台/winform/服务上,并不是一定要依赖IIS才行。
1、首先新建控制台项目,在通过Nuget搜索Microsoft.AspNet.WebApi.SelfHost

2、建立实体类
1 public class Product
2 {
3 public int Id { set; get; }
4 public string Name { set; get; }
5 public string Description { set; get; }
6 }
3、创建WebApi控制器,继承ApiController
1 public class HomeController : ApiController
2 {
3 static List<Product> modelList = new List<Product>()
4 {
5 new Product(){Id=1,Name="电脑",Description="电器"},
6 new Product(){Id=2,Name="冰箱",Description="电器"},
7 };
8
9 //获取所有数据
10 [HttpGet]
11 public List<Product> GetAll()
12 {
13 return modelList;
14 }
15
16 //获取一条数据
17 [HttpGet]
18 public Product GetOne(int id)
19 {
20 return modelList.FirstOrDefault(p => p.Id == id);
21 }
22
23 //新增
24 [HttpPost]
25 public bool PostNew(Product model)
26 {
27 modelList.Add(model);
28 return true;
29 }
30
31 //删除
32 [HttpDelete]
33 public bool Delete(int id)
34 {
35 return modelList.Remove(modelList.Find(p => p.Id == id));
36 }
37
38 //更新
39 [HttpPut]
40 public bool PutOne(Product model)
41 {
42 Product editModel = modelList.Find(p => p.Id == model.Id);
43 editModel.Name = model.Name;
44 editModel.Description = model.Description;
45 return true;
46 }
47 }
4、在Program的Main方法中加上如下代码
1 static void Main(string[] args)
2 {
3 var config = new HttpSelfHostConfiguration("http://localhost:5000"); //配置主机
4
5 config.Routes.MapHttpRoute( //配置路由
6 "API Default", "api/{controller}/{id}",
7 new { id = RouteParameter.Optional });
8
9 using (HttpSelfHostServer server = new HttpSelfHostServer(config)) //监听HTTP
10 {
11 server.OpenAsync().Wait(); //开启来自客户端的请求
12 Console.WriteLine("Press Enter to quit");
13 Console.ReadLine();
14 }
15 }
5、本人机器是win10,如果直接运行是会报错的

解决方法:打开项目路径找到项目名.exe文件右键以管理员身份运行

6、通过url方式访问 http://localhost:5000/api/home

通过winform、服务等方式托管的话本篇不再讲述,方式都类似,我觉得WebApi托管在IIS上是好于其他方式的,用控制台的话演示还是不错的。
下篇讲下WebApi跨域。
