首页 > 代码库 > ASP.NET Web Api OwinSelfHost Restful 使用

ASP.NET Web Api OwinSelfHost Restful 使用

一、前言

总结一下什么是RESTful架构:

  (1)每一个URI代表一种资源;

  (2)客户端和服务器之间,传递这种资源的某种表现层;

  (3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现"表现层状态转化"。

 

二、示例

Restful 路由模板默认没有{action},如有特殊需要,则需要启用属性路由功能配合使用

1.Startup.cs

     public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            // 启用Web API特性路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //删除XML序列化器
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            //配置跨域
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);
       
        }

2.代码示例

 1     [RoutePrefix("home")]
 2     public class HomeController : ApiController
 3     {
 4         // GET api/home
 5         [HttpGet]
 6         public string Get()
 7         {
 8             return "test";
 9         }
10 
11         [HttpGet]
12         // GET api/home/5
13         public string Get(int id)
14         {
15             return id.ToString();
16         }
17 
18         [HttpGet]
19         // GET api/home?name=test
20         public string Get(string name)
21         {
22             return name;
23         }
24 
25         [HttpGet]
26         // GET api/home/1?name=test 
27         //id 能匹配到{id}路由模板
28         public string Get(string name, int id)
29         {
30             return name + id;
31         }
32 
33 
34         // GET api/home/1?name=test&age=30
35         [HttpGet]
36         public string Get(int id, string name, int age)
37         {
38             return id + name + age;
39         }
40 
41         // POST api/home
42         [HttpPost]
43         public void Post(Person p)
44         {
45         }
46 
47 
48         // POST home/post2
49         [HttpPost]
50         [Route("post2")]
51         public void Post2(Person p)
52         {
53         }
54 
55         [HttpPut]
56         // PUT api/home/5
57         public void Put(string id, Person p)
58         {
59         }
60 
61         // PUT home/put2
62         [HttpPut]
63         [Route("put2")] //多个POST或PUT需要走action
64         public void Put2(Person p)
65         {
66         }
67 
68         // DELETE api/home/5
69         [HttpDelete]
70         public void Delete(int id)
71         {
72         }
73 
74         // DELETE api/home/5?type=1&name=test
75         [HttpDelete]
76         public void Delete(int id, string type, string name)
77         {
78         }
79     }

 

ASP.NET Web Api OwinSelfHost Restful 使用