C#(.Net Core WebAPI)之API文檔的生成(Swagger)

一 : 安裝Swagger

Swashbuckle.AspNetCore
在NuGet 中,安裝 Swashbuckle.AspNetCore :
C#(.Net Core WebAPI)之API文檔的生成(Swagger)
我使用的版本爲 : 5.0.0-rc2

二 : 引入Swagger功能

Ⅰ : Startup.cs
① ,ConfigureServices方法中:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options =>
            {
                options.SerializerSettings.Formatting = Formatting.Indented;
            });
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title = "Swagger Test UI",
                    Version = "v1",
                    Description = "Aonaufly first ASP.NET Core Web API"
                });
                options.CustomSchemaIds(type => type.FullName); // 解決相同類名會報錯的問題
                options.IncludeXmlComments(Path.Combine(Directory.GetCurrentDirectory(), "WebAPIPoco.xml")); // 標註要使用的 XML 文檔
                options.DescribeAllEnumsAsStrings();
            });
        }

②: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
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            //設置全局跨域
            app.UseCors(builder => builder.AllowAnyOrigin());
            app.UseHttpsRedirection();
            app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });
            // 在這裏面可以注入
            app.UseSwaggerUI(options =>
            {
                options.ShowExtensions();
                options.ValidatorUrl(null);
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Aonaufly API V1");
                options.DocExpansion(DocExpansion.None);
            });
            app.UseMvc();
        }

三 :配置設置

①,到處項目XML , 加入1591禁止警告
C#(.Net Core WebAPI)之API文檔的生成(Swagger)
②,將項目XML生成路徑複製到項目根路徑
copy $(TargetDir)WebAPIPoco.xml $(ProjectDir)WebAPIPoco.xml
C#(.Net Core WebAPI)之API文檔的生成(Swagger)
③,重置默認網頁爲swagger , 默認是 api/values
C#(.Net Core WebAPI)之API文檔的生成(Swagger)

四 :初始結果

C#(.Net Core WebAPI)之API文檔的生成(Swagger)

五 : 測試

/// <summary>
        /// 帶參數的get請求
        /// </summary>
        /// <remarks>
        /// <code>
        /// 輸入 : int
        /// 輸出 : string
        /// </code>
        /// </remarks>
        /// <param name="id">ID號</param>
        /// <returns>String</returns> 
        /// <response code="201">返回字符串</response>
        /// <response code="400">如果id爲空</response>
        // GET api/values/5
        [HttpGet("{id}")]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

結果:
C#(.Net Core WebAPI)之API文檔的生成(Swagger)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章