asp.net core web api 控制類定義技巧
ation放在類的外部,例如:
???[Route("api/[controller]/[action]")]
? ? [ApiController]
? ? public class SystemInfoController : ControllerBase此種類型,則action對(duì)整個(gè)類起作用,路由訪問的時(shí)候,action可被類的方法名代替:
[Route("api/[controller]/[action]")]
? ? [ApiController]
? ? public class SystemInfoController : ControllerBase
? ? {
????? ? // 請(qǐng)求方式為:?http://localhost:7216/api/SystemInfo/Do1
????? ? [HttpGet]
????? ? public string Do1()
????? ? {
????????? ? return "hello ";
????? ? }
????? ? // 請(qǐng)求方式為:?http://localhost:7216/api/SystemInfo/Do2?id=def
????? ? [HttpGet]
????? ? public string Do2(string id)
????? ? {
????????? ? return "hello: " + id;
????? ? }
????? ? // 請(qǐng)求方式為:?http://localhost:7216/api/SystemInfo/Do3?id=def
????? ? [HttpGet]
????? ? public string Do3(string id)
????? ? {
????????? ? return "good: " + id;
????? ? }注意:..../方法名 + ? + 參數(shù)=?
2.?[action]放在類的方法定義上面,則action 僅僅對(duì)該方法有效,如下:
[Route("api/[controller]")]
? ? [ApiController]
? ? public class SystemManagerController : ControllerBase
? ? {
? ? ? ? // 以下2個(gè)都是http get 方法,但是路由不同,分別為 api/SystemManager、api/SystemManager/1、api/SystemManager/ab/28
? ? ? ? [HttpGet]
? ? ? ? public string GetC()
? ? ? ? {
? ? ? ? ? ? return "hello world";
? ? ? ? }
? ? ? ? [HttpGet("{id}")]
? ? ? ? public string GetD(int id)
? ? ? ? {
? ? ? ? ? ? return "hello world 0:";
? ? ? ? }
? ? ? ? // 注意:[action] 既可以加在類外頭部(對(duì)類起作用),也可以放在方法頭上面(僅對(duì)該方法有用)
? ? ? ? // 方法外面[action]修飾,則訪問方法為:http://localhost:5049/api/SystemManager/GetE/222
? ? ? ? [HttpGet("[action]/{id}")]
? ? ? ? public string GetE(int id)
? ? ? ? {
? ? ? ? ? ? return "hello world 00:" + id;
? ? ? ? }
? ? ? ? // 請(qǐng)求url:http://localhost:5049/api/SystemManager/GetF?id=985
? ? ? ? [HttpGet("[action]")]
? ? ? ? public string GetF(int id)
? ? ? ? {
? ? ? ? ? ? return "hello world 00:" + id;
? ? ? ? }
? ? ? ? [HttpGet("ab/{id}")]? ? // 注意:通過ab來(lái)區(qū)分路由,以便多個(gè)httpget得以調(diào)用
? ? ? ? public string GetDF(int id)
? ? ? ? {
? ? ? ? ? ? return "hello world 1: " + id;
? ? ? ? }
? ? ? ? [HttpGet("abc/{id}")]? ? // 注意:通過ab來(lái)區(qū)分路由,以便多個(gè)httpget得以調(diào)用
? ? ? ? public string GetDFG(int id)
? ? ? ? {
? ? ? ? ? ? return "hello world 2 :"+id;
? ? ? ? }
? ? }
3. 部分截圖


