ASP.NET?Core之Web?API介紹
1.簡單介紹
ASP.NET Core Web API 是 ASP.NET Core MVC 的一個功能。ASP.NET Core MVC 包含了對 Web API 的支持??梢詷?gòu)建多種客戶端的 HTTP 服務(wù)。ASP.NET Core Web API可用于在 .NET Core 上構(gòu)建 RESTful 應(yīng)用程序。
框架包含對 HTTP 內(nèi)容協(xié)商的支持,內(nèi)置支持以 JSON 或 XML 格式化的數(shù)據(jù)。編寫自定義格式化程序已添加對自有格式的支持。
使用鏈接生成對超媒體的支持。啟用對跨資源共享(CORS)的支持,以便 Web API 可以在多個 Web應(yīng)用程序之間共享。
例如,新建一個 API 項目,默認包含一個 ValuesController:
[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } }
默認包含了 GET,POST,PUT,DELETE 這幾個 HTTP 請求操作。這里直接使用特性路由,在控制器上注明 [Route("api/[controller]")]。調(diào)試并打開瀏覽器輸入 https://localhost:5000/api/values ,會返回數(shù)據(jù)。
2.自定義格式化(Format)
ASP.NET Core MVC內(nèi)建支持對相應(yīng)數(shù)據(jù)的格式,用來修正格式或生成客戶端指定的格式。
1.特定格式的操作結(jié)果
某些操作結(jié)果的類型是特定的格式,比如 JsonResult 或 ContentResult 。操作可以總是返回格式為特定格式的具體結(jié)果。比如返回 JsonResult 時將返回 JSON 格式化數(shù)據(jù),而不管客戶端要求的是什么格式。
操作并不要求返回任何特定的類型, MVC 支持任何對象作為返回值。如果操作返回的是 IActionResult 的某個實現(xiàn),并且控制器繼承自 Controller ,那么可以使用更多輔助方法。如果不是,則將使用合適的 IOutputFormatter 實現(xiàn)序列化對象。
若要從繼承 Controller 基類的控制器返回特定格式的數(shù)據(jù),可以使用內(nèi)置的輔助方法 Json 來返回 JSON 格式, 使用 Content 來返回 純文本。操作方法的返回類型必須是指定的結(jié)果類型(如 JsonResult)或 IActionResult。
[HttpGet] public JsonResult Get() { return Json(new User()); }
以上代碼 Content-Type 將返回 application/json。
要想返回純文本格式的數(shù)據(jù),則使用 ContentResult 以及 Content 輔助方法:
[HttpGet] public ContentResult Get() { return Content("result"); }
以上代碼 Content-Type 將返回 test/plan 。 也可以使用一個字符串相應(yīng)類型來實現(xiàn)這個行為:
[HttpGet] public string Get() { return "result"; }
對于具有多個返回類型或選項的復(fù)雜操作,請選擇 IActionResult 作為返回類型。
2.配置格式化程序
如果應(yīng)用程序想支持默認 JSON 之外的格式,可以在 project.json 文件中添加這些額外的依賴項,并配置 MVC 來支持。輸入和輸出的格式是可以隔離的。輸入格式通過使用模型綁定,輸出格式通過格式化響應(yīng)。
3.添加對 XML 格式的支持
要添加對 XML 格式的支持,需要先安裝 Microsoft.AspNetCore.Mvc.Formatters.Xml 包,然后在 ConfigureServices 中配置 XmlSerializerFormatters :
services.AddMvc() .AddXmlSerializerFormatters() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
或者可以只添加輸出格式:
services.AddMvc(options => { options.OutputFormatters.Add(new XmlSerializerOutputFormatter()); }) //.AddXmlSerializerFormatters() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
這兩種方法都將使用 System.Xml.Serialization.XmlSerializer 序列化結(jié)果。還可以通過添加其他相關(guān)格式來使用 System.Runtime.Serialization.DataContractSerializer :
services.AddMvc(options => { options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); }) //.AddXmlSerializerFormatters() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
4.強制特定格式化
若是想為某個操作限制響應(yīng)格式,則可以使用 [Produces] 過濾器。[Produces] 過濾器可以為這個控制器或 Action 指定響應(yīng)格式:
[HttpGet("{id}", Name = "Get")] [Produces("application/json")] public string Get(int id) { return "value"; }
對于一些特殊情況,可能不想使用內(nèi)建的格式化實現(xiàn)。默認情況下,返回類型為 string 時將格式化為 text/plain 。這種行為可以通過移除 TextOutputFormatter 來改變:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.OutputFormatters.RemoveType<TextOutputFormatter>(); options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>(); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
上面移除了 TextOutputFormatter 和 HttpNoContentOutputFormatter,當(dāng)返回類型為 string 時,將返回 406 Not Acceptable。如果存在 XML 格式化程序,則將格式化響應(yīng)結(jié)果。
移除了 HttpNoContentOutputFormatter ,當(dāng)返回某個返回類型為模型對象的操作返回 null 時,將返回 204 No Content 響應(yīng)。JSON 格式將簡單地返回主體信息為 null 的響應(yīng),而 XML 格式將返回一個空的帶有 xsi:nil="true" 屬性的 XML 元素。
5.響應(yīng)格式 URL 映射
客戶端可以在 URL 中請求特定的格式,比如在請求字符串或路徑中,或者通過使用特定格式的文件擴展名(比如 .xml 或 .json),需要在 API 所使用的路由中指定:
[FormatFilter] public class UserController : Controller { // GET: api/User [HttpGet] [Route("[controller]/[action]/{id}.{format?}")] public IActionResult GetById(int id) { return Content("xxx"); } }
這個路由配置將允許使用可選的文件擴展名來指定格式。[FormatFilter] 特性將在 RouteData 中檢查該格式的值是否存在,并創(chuàng)建響應(yīng)時將響應(yīng)數(shù)據(jù)映射到相應(yīng)的格式:
RouteFormatter
/User/GetById/5 :默認輸出格式
/User/GetById/5.json :JSON格式(如果配置過)
/User/GetById/5.xml; :XML格式(如果配置過)
6.自定義格式化程序 Protocol Buffers (簡稱 protobuf)
Protocol Buffers 是一種輕便高效的結(jié)構(gòu)化數(shù)據(jù)存儲格式,可用于結(jié)構(gòu)化數(shù)據(jù)串行化,或者說序列化。它很適合做數(shù)據(jù)存儲或 RPC(遠程過程調(diào)用協(xié)議)數(shù)據(jù)交換格式??捎糜谕ㄓ崊f(xié)議,數(shù)據(jù)存儲等領(lǐng)域的語言無關(guān),平臺無關(guān),可擴展的序列化結(jié)構(gòu)數(shù)據(jù)格式。比如實現(xiàn)一個程序返回 protobuf 格式:
創(chuàng)建 API 項目,添加 protobuf-net 引用。
添加 ProtobufFormatter 類:
public class ProtobufFormatter:OutputFormatter { public string ContentType { get; private set; } public ProtobufFormatter() { ContentType = "application/proto"; SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/proto")); } public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var response = context.HttpContext.Response; Serializer.Serialize(response.Body,context.Object); return Task.FromResult(0); } }
繼承 OutputFormatter ,然后實現(xiàn) WriteResponseBodyAsync 方法,初始化時賦值 ContentType ,并添加支持 MediaType。在 WriteResponseBodyAsync 方法中獲取 Response ,調(diào)用 protobuf-net 的 Serializer.Serialize 方法將 Object 序列化至輸出內(nèi)容。 protobuf 在序列化時必須指定順序,添加 User 類,實現(xiàn) protobuf 實體:
[ProtoContract] public class User { [ProtoMember(1)] public int Id { get; set; } [ProtoMember(2)] public string Name { get; set; } [ProtoMember(3)] public int Age { get; set; } }
類上需要添加 [ProtoContract] 特性,字段上需要 ProtoMember 特性,并指定順序。然后修改 UserController:
[Route("api/[controller]")] [ApiController] [FormatFilter] public class UserController : Controller { private IEnumerable<User> users; public UserController() { users = new User[] { new User(){ Id=1,Name="Bob",Age = 20}, new User(){ Id=2,Name="Tom",Age = 22} }; } // GET: api/User [HttpGet] [Produces("application/proto")] public IEnumerable<User> Get() { return users; } }
修改 ConfigureServices :
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.OutputFormatters.Add(new ProtobufFormatter()); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
運行程序,會返回一個二進制文件。
創(chuàng)建一個控制臺,檢查序列化:
class Program { static void Main(string[] args) { HttpClient client = new HttpClient(); var stream = client.GetStreamAsync("https://localhost:44358/api/User").Result; var users = Serializer.Deserialize<List<User>>(stream); foreach (var user in users) { Console.WriteLine($"Id:{user.Id} - Name:{user.Name} - Age:{user.Age}"); } Console.ReadKey(); } }
到此這篇關(guān)于ASP.NET Core Web API的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
.Net結(jié)構(gòu)型設(shè)計模式之外觀模式(Facade)
這篇文章介紹了.Net結(jié)構(gòu)型設(shè)計模式之外觀模式(Facade),文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05詳解ABP框架的參數(shù)有效性驗證和權(quán)限驗證
ABP框架是基于ASP.NET的Web開發(fā)框架(GitHub: https://github.com/aspnetboilerplate),在ASP.NET框架之上又添加了更強大的功能,這里我們就來詳解ABP框架的參數(shù)有效性驗證和權(quán)限驗證2016-06-06.Net行為型設(shè)計模式之備忘錄模式(Memento)
這篇文章介紹了.Net行為型設(shè)計模式之備忘錄模式(Memento),文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05ASP.NET?Core開發(fā)環(huán)境安裝配置
這篇文章介紹了ASP.NET?Core開發(fā)環(huán)境安裝配置,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02創(chuàng)建ASP.NET?Core?Web應(yīng)用程序并介紹項目模板
這篇文章介紹了創(chuàng)建ASP.NET?Core?Web應(yīng)用程序的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02