標籤:程式
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 order builder.AddFormatterMappings(); builder.AddViews(); builder.AddRazorViewEngine(); builder.AddCacheTagHelper(); // +1 order builder.AddDataAnnotations(); // +1 order // +10 order builder.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"}
在ASP.NET Core MVC中構建簡單 Web Api