在ASP.NET Core MVC中构建简单 Web Api
????
Getting Started
在 ASP.NET Core MVC 框架中,ASP.NET 團隊為我們提供了一整套的用于構建一個 Web 中的各種部分所需的套件,那么有些時候我們只需要做一個簡單的 Web Api 程序怎么辦呢?
在 GitHub 中的 ASP.NET Core MVC 源碼里面,我們只要關注?Microsoft.AspNetCore.Mvc?這個包,那么除了這個包之外它還包含這些:
Microsoft.AspNetCore.Mvc.ApiExplorer
Microsoft.AspNetCore.Mvc.Cors
Microsoft.AspNetCore.Mvc.DataAnnotations
Microsoft.AspNetCore.Mvc.Formatters.Json
Microsoft.AspNetCore.Mvc.Localization
Microsoft.AspNetCore.Mvc.Razor
Microsoft.AspNetCore.Mvc.TagHelpers
Microsoft.AspNetCore.Mvc.ViewFeatures
Microsoft.Extensions.Caching.Memory
Microsoft.Extensions.DependencyInjection
NETStandard.Library
通常情況下,我們在創建一個 Web MVC 網站的時候,會在 Startup.cs 文件中的?ConfigureServices?方法中,這樣添加:
services.AddMvc();以上的代碼會將 MVC 中的服務注入到 DI 容器中,我們來看一下?AddMvc()?的源碼:
public?static?IMvcBuilder?AddMvc(this?IServiceCollection?services){????var?builder?=?services.AddMvcCore();builder.AddApiExplorer();builder.AddAuthorization();AddDefaultFrameworkParts(builder.PartManager);????//?Order?added?affects?options?setup?order//?Default?framework?orderbuilder.AddFormatterMappings();builder.AddViews();builder.AddRazorViewEngine();builder.AddCacheTagHelper();????//?+1?orderbuilder.AddDataAnnotations();?//?+1?order//?+10?orderbuilder.AddJsonFormatters();builder.AddCors();????return?new?MvcBuilder(builder.Services,?builder.PartManager); }簡單 Web Api
實際上,如果想構建一個簡單 Web Api 程序的話,ASP.NET 團隊已經為我們想到了這一點,所以我們只需要修改我們注入的服務。
首先,不需要引用?Microsoft.AspNetCore.Mvc?這個包了,轉而引用?Microsoft.AspNetCore.Mvc.Core。 Mvc.Core 這個包只會給你提供基本的 MVC 中間件,比如路由,Controller, HttpResult 等,其他更多的如關于 Razor,Cores,Views 等則沒有提供。
在 Web Api 應用中,大多數情況下是以 Json 進行數據序列化傳輸的,所以需要添加?Microsoft.AspNetCore.Mvc.Formatters.Json?這個包。
然后,在?ConfigureServices?,將 Mvc Core 中間件和 Json Formatter 添加里面。
public?void?ConfigureServices(IServiceCollection?services){services.AddMvcCore().AddJsonFormatters(); }最后一點就是,你的 XXXController 類中要繼承?ControllerBase?而不是?Controller。 ControllerBase 里面沒有提供任何關于對 Views 的支持。
public?class?XXXController:?ControllerBase{ }下面是最終的 project.json 引用的所有程序包。
"dependencies":?{????"Microsoft.NETCore.App":?{??????"version":?"1.1.0",??????"type":?"platform"},????"Microsoft.AspNetCore.Mvc.Core":?"1.1.0",????"Microsoft.AspNetCore.Mvc.Formatters.Json":?"1.1.0",????"Microsoft.AspNetCore.Server.IISIntegration":?"1.1.0",????"Microsoft.AspNetCore.Server.Kestrel":?"1.1.0",????"Microsoft.Extensions.Configuration.EnvironmentVariables":?"1.1.0",????"Microsoft.Extensions.Configuration.FileExtensions":?"1.1.0",????"Microsoft.Extensions.Configuration.Json":?"1.1.0",????"Microsoft.Extensions.Configuration.CommandLine":?"1.1.0",????"Microsoft.Extensions.Logging":?"1.1.0",????"Microsoft.Extensions.Logging.Console":?"1.1.0",????"Microsoft.Extensions.Logging.Debug":?"1.1.0"}轉載于:https://blog.51cto.com/12879490/1923158
總結
以上是生活随笔為你收集整理的在ASP.NET Core MVC中构建简单 Web Api的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 20155225 实验三《敏捷开发与XP
- 下一篇: HTML5 进阶系列:indexedDB