Web APi入門之Self-Host(二)


這篇來講講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跨域。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM