[Swagger&ExtensionService] Adding Swagger and Extensions to ASP.NET Core Web API using XML Documentation
Adding Swagger and Extensions to ASP.NET Core Web API using XML Documentation
之前一直在想,很多服務與設定檔都集中在 Startup.cs 裡面,可是東西服務很多,整個 Configure 與 ConfigureServices 就會越來越肥,但是很不喜歡這樣,很想把類似相關聯的東西集中在一起。Google 看看,做筆記一些筆記,順便研究該怎麼把那些東西從 Startup 中抽離出來。
Startup
Startup 類似是以前 ASP.NET 的 Global.asax。它掌管整個系統的設定檔,與要運行那些服務到管線中。它主要分成兩個部分,一個是 Configure 與 ConfigureServices。
ConfigureServices
ConfigureServices 主要是掌管註冊服務到的ASP.NET Core的服務容器。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);         
}
Configure
Configure 主要是將要運行的程式或是路由一些設定到後續程式運行的管線中。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseMvc();
}
Extensions
新增 Extensions,Extensions 主要是用來擴展程式的框架,例如,註冊服務與一些系統設定檔。將一些註冊的服務(ConfigureServices)或是將要運行的程式(Configure), 從上述的東西抽離到 Extensions 的程式裡。
以 Swagger 為例
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    // Swagger 
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
        {
            Title = "Swagger XML API Demo",
            Version = "V1",
        });
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseMvc();
    // Swagger 
    app.UseSwagger();
    app.UseSwaggerUI(c => {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger XML API Demo V1");
    });
}
如果有超過十個以上的服務,意味著整個 Startup 程式會越來越臃腫肥大,對將來追蹤系統將會是一個很大的負擔。所以新增自己的 ServicesExtensions,建立 SwaggerServiceExtensions.cs 。
public static class SwaggerServiceExtensions
{
    public static void ConfigureSwagger(this IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
            {
                Title = "Swagger XML API Demo",
                Version = "V1",
            });
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            c.IncludeXmlComments(xmlPath);
        });
    }
    public static IApplicationBuilder SwaggerSettings(this IApplicationBuilder app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger XML API Demo V1");
        });
        return app;
    }
}
調整 Startup 中原先的 Code,並呼叫 Extensions 的方法,執行應該會看見一樣的結果。
// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // DI Swagger to Service Container
            services.ConfigureSwagger();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseMvc();
            // Run Swagger Settings and Application to Pipeline
            app.SwaggerSettings();
        }
另外,可以善用註解,透過 Swagger ,幫系統建立良好的 API 。
開啟整個專案的屬性檔,在 Build 的地方,將 Output 的 XML Documentation file 打開。
Note : 是否要修改 Error and Warnings 的 Suppress warnings 內容,將 1591 加入,在編譯時會提示那些方法或是類別沒有填寫註解內容。
留言
張貼留言