.Net Core Web Api 2 的 restful、路由設定、request、response 範例

 

以下示範基本的 web api 範例

一、簡單的 GET、POST、PUT、DELETE 範例示範如下
示範當一個 controller 只存在一隻 api 時的預設 restful 範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
private static List<Person> _persons = new List<Person>();

[HttpGet] // ~/Person
public IEnumerable<Person> GetMethod()
{
return _persons;
}

[HttpPost] // ~/Person
public string PostMethod(int id, string name)
{
_persons.Add(new Person() { Id = id, Name = name });
return "add success";
}

[HttpPut] // ~/Person
public string PutMethod(int id, string name)
{
_persons.Where(x => x.Id == id).First().Name = name;
return "put success";
}

[HttpDelete] // ~/Person
public string DeleteMethod(int id)
{
_persons.Remove(_persons.Where(x => x.Id == id).FirstOrDefault());
return "delete success";
}

}

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}

}


二、api route 的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
private static List<Person> _persons = new List<Person>();

[HttpGet] // ~/Person
public IEnumerable<Person> GetMethod()
{
return _persons;
}

[HttpPost] // ~/Person
public string PostMethod(int id, string name)
{
_persons.Add(new Person() { Id = id, Name = name });
return "add success";
}

[HttpPut] // ~/Person
public string PutMethod(int id, string name)
{
_persons.Where(x => x.Id == id).First().Name = name;
return "put success";
}

[HttpDelete] // ~/Person
public string DeleteMethod(int id)
{
_persons.Remove(_persons.Where(x => x.Id == id).FirstOrDefault());
return "delete success";
}


/* 路由的使用 */
[HttpGet("{id}")] // ~/Person/{id}
public Person GetMethod(int id)
{
return _persons.First(x => x.Id == id);
}

[HttpGet("Lv1")] // ~/Person/Lv1
public string GetLv1()
{
return "~/Person/Lv1";
}

[HttpGet("Lv1/Lv2")] // ~/Person/Lv1/Lv2
public string GetLv2()
{
return "~/Person/Lv1/Lv2";
}

[HttpGet("/Lv1/Lv2/Lv3")] // ~/Lv1/Lv2/Lv3
public string GetLv3()
{
return "~/Lv1/Lv2/Lv3";
}

[HttpGet("/Lv1/Lv2/Lv3/{id}")] // ~/Lv1/Lv2/Lv3/{id}
public string GetLv3ById(int id)
{
return "~/Lv1/Lv2/Lv3/" + id;
}

}

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}

}


三、request 的型式 (Model binding)
request 的型式可為 FromRoute、FromQuery、FromBody、FromForm,範例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
private static List<Person> _persons = new List<Person>();

[HttpGet] // ~/Person
public IEnumerable<Person> GetMethod()
{
return _persons;
}

[HttpPost] // ~/Person
public string PostMethod(int id, string name)
{
_persons.Add(new Person() { Id = id, Name = name });
return "add success";
}

[HttpPut] // ~/Person
public string PutMethod(int id, string name)
{
_persons.Where(x => x.Id == id).First().Name = name;
return "put success";
}

[HttpDelete] // ~/Person
public string DeleteMethod(int id)
{
_persons.Remove(_persons.Where(x => x.Id == id).FirstOrDefault());
return "delete success";
}



/* Model binding 的型式 */
// 1.FromRoute
[HttpGet("{id}")] // ~/Person/{id}
public Person GetMethod([FromRoute] int id)
{
return _persons.First(x => x.Id == id);
}

// 2.FromQuery 寫法1
[HttpGet("DefaultQuery")] // ~/Person/DefaultQuery?id=123
public Person GetDefaultFromQuery(int id)
{
return _persons.First(x => x.Id == id);
}

// 2.FromQuery 寫法2
[HttpGet("Query")] // ~/Person/Query?id=123
public Person GetFromQuery([FromQuery] int id)
{
return _persons.First(x => x.Id == id);
}

// 2.FromQuery 寫法3
[Route("RouteAttribute")]
[HttpGet] // ~/Person/RouteAttribute?id=123
public string GetRouteAttribute([FromQuery] int id)
{
return "~/Person/RouteAttribute?id=123";
}

// 3.FromBody,注意 FromBody 不能用在 HttpGet 方式
[HttpPost("Body")] // ~/Person/Body
public Person GetFromBody([FromBody] Person p)
{
return _persons.First(x => x.Id == p.Id);
}

// 4.可以同時使用 FromQuery 與 FromBody
[HttpPost("Body/Verify")] // ~/Person/Body/Verify?VerifyCode=777
public Person GetFromQueryAndFromBody([FromQuery] string verifyCode, [FromBody] Person p)
{
if (verifyCode == "777")
return _persons.First(x => x.Id == p.Id);
else
return null;
}

// 5.FromForm,注意 FromForm 只能使用 HttpPost 方式
// FromForm 可以用來處理檔案上傳,可用 IFormFile 或 IFormFileCollection 型態來接
[HttpPost("Form")] // ~/Person/Form
public Person GetFromForm([FromForm] Person p)
{
return _persons.First(x => x.Id == p.Id);
}

}

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}

}


四、使用 ProducesAttribute 來指定 response 的型式
如下程式範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
private static List<Person> _persons = new List<Person>();

[HttpGet] // ~/Person
public IEnumerable<Person> GetMethod()
{
return _persons;
}

[HttpPost] // ~/Person
public string PostMethod(int id, string name)
{
_persons.Add(new Person() { Id = id, Name = name });
return "add success";
}

[HttpPut] // ~/Person
public string PutMethod(int id, string name)
{
_persons.Where(x => x.Id == id).First().Name = name;
return "put success";
}

[HttpDelete] // ~/Person
public string DeleteMethod(int id)
{
_persons.Remove(_persons.Where(x => x.Id == id).FirstOrDefault());
return "delete success";
}



/* 指定 response type */
[HttpGet("DefaultResponseTextPlain")] // ~/Person/DefaultResponseTextPlain
public IEnumerable<Person> GetDefault()
{
return _persons;
}

[HttpGet("ResponseJson")] // ~/Person/ResponseJson
[Produces("application/json")]
public IEnumerable<Person> GetJson()
{
return _persons;
}

[HttpGet("ResponseXml")] // ~/Person/ResponseXml
[Produces("text/xml")]
public IEnumerable<Person> GetXml()
{
return _persons;
}

}

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}

}

特別注意,如果你要能接收 XML 格式的 request 的話,除了於上面程式碼加上 [Produces(“text/xml”)] 之外,
你還需要在 Program.cs 裡添加一段如下程式碼

1
builder.Services.AddControllers().AddXmlSerializerFormatters();

參考資料:
ASP. NET Web Api 2 學習筆記
Model Binding in ASP.NET Core