影片講解(有字幕)
首先一開始專案已經有一個範本的API
那基本上我們會將API接口,也就是XXController統一放在Controllers資料夾下,命名規則會使用[名稱]Controller,就像範例的WeatherForecastController.cs,會以Controller做結尾。
那我們今天要產生一個新的Controller就如上圖,在Controllers資料夾上按右鍵,選擇加入>新增項目>執行讀取/寫入動作的API控制器
那其實就是個cs檔,但會加上API接口所需要的程式碼片段,也就是一個先幫你寫好基本架構的範本。你也可以選擇API控制器-空白,就是少了新增、讀取、修改、刪除的程式碼,你自己再加上去也可以,但我通常我選擇>執行讀取/寫入動作的API控制器。那我們名字就取名為
HelloWorldController.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Todo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HelloWorldController : ControllerBase
{
// GET: api/<HelloWorldController>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<HelloWorldController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<HelloWorldController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<HelloWorldController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<HelloWorldController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
就會產生上述內容,空白的則沒有public class HelloWorldController
內的程式碼,那我們新增好後,馬上就可以執行了,按下啟動不偵錯察看結果。並且在網址上打上/api/helloworld就會出現回應。
接著我們修改一下程式碼,將value1、2分別打上hello、world
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "hello", "world" };
}
我們直接對瀏覽器做重新整理,就可以看到新的結果了。
接下來,我們稍微來了解一下這個Controller的基本架構。
public class HelloWorldController : ControllerBase
一個類別繼承了ControllerBase
之後,會擁有一些Web API所需的基本功能
[ApiController]
則會讓這個Web API啟用一些固定API特有的行為,可參考這裡,後面也會再次提到。
[Route("api/[controller]")]
這是改變Web API路由網址的標籤,其中[controller]的部分會對應到上方class name的Controller之前的英文,所以我們這支Web API的網址會是api/helloworld,另外在這邊大小寫是不拘的,視為同一個。
那為什麼範本的網址會是WeatherForecast而已呢?可以仔細看它上面的[Route("[controller]")]
其實並沒跟我們剛剛產生的範本一樣有加api
所以說今天在Core這邊想改變Web API的網址就變得很簡單又直覺,你只要在class上方設好你想要的Route路徑,就能夠改變。
那我們在往下看class裡面的方法
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "hello", "world" };
}
可以看到上面有著[HttpGet]
的標籤,這個也是可以用來控制路由網址,但多了一個功能,就是可以決定client的要求的method,也就是說你必須用get方法,才會進到這個function裡面,下面還有各種標籤([HttpPost]、[HttpPut("{id}")]、[HttpDelete("{id}")]
)各對應著不同方法。
其中[HttpGet("{id}")]
標籤裡面也可以再次進行網址路由的改變,所以這支網址會變成api/helloword/{id},其中用{}代表這是可接收的參數。
[HttpGet("{id}")]
public int Get(int id)
{
return id;
}
我們可以在function接受參數的位置,打上跟{}同名的變數,像上面的例子就是打上id,那型別則可自行決定,會幫你自動做轉換,但前提是要轉的過去,不然會失敗,例如你打api/helloworld/a,但你打int型別就會錯誤,因為傳過來的是a。
如果api/helloworld/1,則畫面就正確回傳1
以上就是簡單的第一支HelloWorld的簡單示範。想要聽多一些廢話的可以看影片
新手分享學習成果,若有錯誤,煩請告知修正,感謝🙏