上篇文章,我們試着調用API,成功返回值,今天接下來看看代碼是怎么構成的

1 [Route("api/[controller]")] 2 [ApiController] 3 public class TodoController : ControllerBase 4 { 5 private readonly TodoContext _context; 6 7 public TodoController(TodoContext context) 8 { 9 _context = context; 10 11 if (_context.TodoItems.Count() == 0) 12 { 13 // Create a new TodoItem if collection is empty, 14 // which means you can't delete all TodoItems. 15 _context.TodoItems.Add(new TodoItem { Name = "Item1" }); 16 _context.SaveChanges(); 17 } 18 } 19 20 21 // GET: api/Todo 22 [HttpGet] 23 public ActionResult<IEnumerable<TodoItem>> GetDataList() 24 { 25 return _context.TodoItems.ToList(); 26 } 27 [HttpPost] 28 public IActionResult Create( TodoItem item) 29 { 30 if (item == null) 31 { 32 return BadRequest(); 33 } 34 35 _context.TodoItems.Add(item); 36 _context.SaveChanges(); 37 38 return CreatedAtRoute("GetTodo", new { id = item.Id }, item); 39 } 40 [HttpPut("{id}")] 41 public IActionResult Update(long id, [FromBody] TodoItem item) 42 { 43 if (item == null || item.Id != id) 44 { 45 return BadRequest(); 46 } 47 48 var todo = _context.TodoItems.FirstOrDefault(t => t.Id == id); 49 if (todo == null) 50 { 51 return NotFound(); 52 } 53 54 todo.IsComplete = item.IsComplete; 55 todo.Name = item.Name; 56 57 _context.TodoItems.Update(todo); 58 _context.SaveChanges(); 59 return new NoContentResult(); 60 } 61 [HttpDelete("{id}")] 62 public IActionResult Delete(long id) 63 { 64 var todo = _context.TodoItems.FirstOrDefault(t => t.Id == id); 65 if (todo == null) 66 { 67 return NotFound(); 68 } 69 70 _context.TodoItems.Remove(todo); 71 _context.SaveChanges(); 72 return new NoContentResult(); 73 } 74 // GET: api/Todo/5 75 [HttpGet("{id}")] 76 public async Task<ActionResult<TodoItem>> GetTodoItem(long id) 77 { 78 var todoItem = await _context.TodoItems.FindAsync(id); 79 80 if (todoItem == null) 81 { 82 return NotFound(); 83 } 84 85 return todoItem; 86 } 87 }
首先我們的方法都寫在Controller里面,這個Controller必須繼承基類 ControllerBase
每個暴露給外面的接口方法都是public ,為了表明方法是post 或Get, 在方法的上面標注[HttpPost]或[HttpGet],這是一種約定,這是一種規范。
在這里有兩個注意點.如果方法不標注,則Get和Post方法都支持,但是同時只能有一個對外開放的方法不標注
下面我們來驗證下結論,方法不標注用Get方法調用
看,雖然HTTPGet注釋了,但是方法還是成功的被調用
同樣的 post 方法也能成功調用
為啥只能有一個API方法可以不標注,如果本來就已經標注了Get方法,不標注的方法還可以是Get方法嗎?如果我們要有2個以上get方法是否可以,帶着這些疑問,我們下篇文章再來驗證。