平時 API 的回應(response) HTTP 狀態代號(status code) 基本上都是代表成功的 200 ,只是對於新增/建立來說,回應應該是要 201 ,表示已經建立。並且在 Header 中通常也會多 Location 內容,附帶指向能夠讀取新建立資源的連結。
下面就來示範在 ASP.NET Core API 如何回應 201 和加上 Location Header。
這個範例有兩個 API ,可以查詢和新增使用者,這是一個簡單的示範,建立和查詢都是使用假的資料。
除了取得 Action 的名稱外,也可以使用路由的自訂名稱來取得:
參考資料:
mdn web docs - 201 Created
mdn web docs - Location Headers
下面就來示範在 ASP.NET Core API 如何回應 201 和加上 Location Header。
這個範例有兩個 API ,可以查詢和新增使用者,這是一個簡單的示範,建立和查詢都是使用假的資料。
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
/// <summary>
/// 使用者資料傳輸物件
/// </summary>
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; }
}
/// <summary>
/// 依照 id 取得使用者資料
/// </summary>
[HttpGet("{id:int}")]
public ActionResult<UserDto> GetUser(int id)
{
// 這是一個假的取得使用者
return new UserDto
{
Id = id,
Name = $"User{id}",
};
}
/// <summary>
/// 新增使用者
/// </summary>
[HttpPost]
public ActionResult<UserDto> CreateUser(UserDto user)
{
return CreatedAtAction(
nameof(GetUser), // Location Header 指向的 Action
new { id = user.Id }, // Location Header 指向的 Action 的參數
user // 回傳的內容,是建立成功的完整的資料
);
}
}
除了取得 Action 的名稱外,也可以使用路由的自訂名稱來取得:
[HttpGet("{id:int}", Name = "GetAUser")]
public ActionResult<UserDto> GetUser(int id)
{
// 這是一個假的取得使用者
return new UserDto
{
Id = id,
Name = $"User{id}",
};
}
[HttpPost]
public ActionResult<UserDto> CreateUser(UserDto user)
{
return CreatedAtRoute(
"GetAUser",
new { id = user.Id },
user
);
}
參考資料:
mdn web docs - 201 Created
mdn web docs - Location Headers
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com