Restful幾乎已算是API設計的標準,經過HTTP Method區分新增(Create)、查詢(Read)、修改(Update)和刪除(Delete),簡稱CRUD四種數據存取方式,簡約又直接的風格,讓人用的愛不釋手。
本篇將介紹如何經過ASP.NET Core實踐REST-Like API。javascript
本文API設計未符合HATEOAS(Hypermedia As The Engine Of Application State)原則,因此不得稱爲RESTful API。html
RESTful API 有四個重要的原則要遵照:java
REST-Like API 對數據的操做行爲,經過HTTP Method 分爲如下四種方式:git
新增(Create)
用HTTP POST
經過Body傳遞JSON或XML格式的數據給Server。例如:github
POST http://localhost:5000/api/users
{
"id": 1,
"name": "SnailDev"
}
查詢(Read)
用HTTP GET通
過URL帶查詢參數。一般查詢單一資源會用路由參數(Routing Parameter)帶上惟一值(Primary Key);多筆查詢會用複數,而查詢條件用Query String。例如:api
# 單筆查詢
GET http://localhost:5000/api/users/1
# 多筆查詢
GET http://localhost:5000/api/users
# 多筆查詢帶條件
GET http://localhost:5000/api/users?q=SnailDev
修改(Update)
修改數據如同查詢跟新增的組合,用HTTP PUT通
過URL帶路由參數,找到要修改的目標;再經過Body傳遞JSON或XML格式的數據給Server。例如:bash
PUT http://localhost:5000/api/users/1
{
"name": "SnailDev"
}
刪除(Delete)
刪除數據同查詢,用HTTP DELETE
經過URL帶路由參數,找到要刪除的目標。例如:app
DELETE http://localhost:5000/api/users/1
ASP.NET Core 2 學習筆記(六)MVC 有提到,過去ASP.NET MVC把MVC及Web API的套件分開,但在ASP.NET Core中MVC及Web API用的套件是相同的。因此只要裝Microsoft.AspNetCore.Mvc
套件就能夠用Web API了。路由方式也跟ASP.NET Core 2 學習筆記(七)路由 介紹的RouteAttribute
差很少,只是改用HTTP Method Attribute。post
HTTP Method Attribute 符合RESTful 原則的路由設定方式以下:學習
[Route("api/[controller]s")]
public class UserController : Controller
{
[HttpGet]
public List<UserModel> Get(string q)
{
// ...
}
[HttpGet("{id}")]
public UserModel Get(int id)
{
// ...
}
[HttpPost]
public int Post([FromBody]UserModel user)
{
// ...
}
[HttpPut("{id}")]
public void Put(int id, [FromBody]UserModel user)
{
// ...
}
[HttpDelete("{id}")]
public void Delete(int id)
{
// ...
}
}
目前ASP.NET Core 尚未像ASP.NET MVC 的MapHttpAttributeRoutes 能夠綁Http Method 的全局路由,都要在Action 加上HTTP Method Attribute。
用如下代碼,說明SerializerSettings
:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
}
// ...
[Route("api/[controller]s")]
public class UserController : Controller
{
[HttpGet("{id}")]
public UserModel Get(int id)
{
return new UserModel {
Id = 1,
Name = "SnailDev"
};
}
}
過去ASP.NET Web API 2預設是Pascal Case;而ASP.NET Core預設是使用camel Case。
若想要指定用ContractResolver
,能夠在Startup.cs
的ConfigureServices
加入MVC服務時,使用AddJsonOptions
設定以下:
// ...
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver
= new CamelCasePropertyNamesContractResolver();
});
// 同如下寫法:
// services.AddMvc();
}
}
訪問http://localhost:5000/api/users/1
會返回JSON以下:
{
"id": 1,
"name": "SnailDev",
"email": null,
"phoneNumber": null,
"address": null
}
若想保持跟ASP.NET Web API 2同樣使用Pascal Case,ContractResolver
則改用DefaultContractResolver
。
// ...
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver
= new DefaultContractResolver();
});
}
}
DefaultContractResolver
名稱是延續ASP.NET,雖然名稱叫Default,但在ASP.NET Core它不是Default。CamelCasePropertyNamesContractResolver
纔是ASP.NET Core的Default ContractResolver。
訪問http://localhost:5000/api/users/1
會返回JSON以下:
{
"Id": 1,
"Name": "SnailDev",
"Email": null,
"PhoneNumber": null,
"Address": null
}
上述兩個JSON 回傳,都帶有null 的字段。在序列化的過程,找不到字段會自動轉成null,傳送的過程忽略掉也沒錯,反而能夠節省到一點流量。
// ...
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling
= Newtonsoft.Json.NullValueHandling.Ignore;
});
}
}
訪問http://localhost:5000/api/users/1
會返回JSON以下:
{
"id": 1,
"name": "SnailDev"
}
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling
= Newtonsoft.Json.NullValueHandling.Ignore;
});
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
}
Models\ResultModel.cs
namespace MyWebsite.Models
{
public class ResultModel
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public object Data { get; set; }
}
}
用一個ResultModel 來包裝每一個API 回傳的內容,不論調用Web API 成功失敗都用此對象包裝,避免直接throw exception 到Client,產生HTTP Status 200 之外的狀態。
Controllers/UserController.cs
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using MyWebsite.Models;
namespace MyWebsite.Controllers
{
[Route("api/[controller]s")]
public class UserController : Controller
{
private static List<UserModel> _users = new List<UserModel>();
[HttpGet]
public ResultModel Get(string q)
{
var result = new ResultModel();
result.Data = _users.Where(c => string.IsNullOrEmpty(q)
|| Regex.IsMatch(c.Name, q, RegexOptions.IgnoreCase));
result.IsSuccess = true;
return result;
}
[HttpGet("{id}")]
public ResultModel Get(int id)
{
var result = new ResultModel();
result.Data = _users.SingleOrDefault(c => c.Id == id);
result.IsSuccess = true;
return result;
}
[HttpPost]
public ResultModel Post([FromBody]UserModel user)
{
var result = new ResultModel();
user.Id = _users.Count() == 0 ? 1 : _users.Max(c => c.Id) + 1;
_users.Add(user);
result.Data = user.Id;
result.IsSuccess = true;
return result;
}
[HttpPut("{id}")]
public ResultModel Put(int id, [FromBody]UserModel user)
{
var result = new ResultModel();
int index;
if ((index = _users.FindIndex(c => c.Id == id)) != -1)
{
_users[index] = user;
result.IsSuccess = true;
}
return result;
}
[HttpDelete("{id}")]
public ResultModel Delete(int id)
{
var result = new ResultModel();
int index;
if ((index = _users.FindIndex(c => c.Id == id)) != -1)
{
_users.RemoveAt(index);
result.IsSuccess = true;
}
return result;
}
}
}
經過Postman 測試API。
Routing in ASP.NET Core
Attribute Routing in ASP.NET Core
Richardson Maturity Model
HATEOAS
老司機發車啦:https://github.com/SnailDev/SnailDev.NETCore2Learning