在webapi中使用swagger


1 在webapi項目下安裝swagger,包名 Swashbuckle.AspNetCore

2 在webapi的startup.cs文件中添加swagger服務

/// <summary>
        /// 配置服務 注冊服務
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v0.1.0",
                    Title = "學習Swagger",
                    Description = "框架說明文檔",
                    TermsOfService = "None",
                    Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "Learn.Swagger", Email = "king@net.com", Url = "https://www.facai.com" }
                });
                //如果不加入以下兩個xml 也是可以的 但是不會對api有中文說明,使用了一下兩個xml 就需要對成員使用///注釋
                //本webapi的xml
                var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "Learn.Swagger.xml");//這個就是剛剛配置的xml文件名
                c.IncludeXmlComments(xmlPath, true);//默認的第二個參數是false,這個是controller的注釋,記得修改


                //如果不引用別的類庫項目,那么以上就是一個webapi項目添加swagger服務的全部


                //webapi引用model的xml 
                var xmlModelPath = Path.Combine(basePath, "Learn.Swagger.Model.xml");//這個就是Model層的xml文件名
                c.IncludeXmlComments(xmlPath, true);//默認的第二個參數是false,這個是controller的注釋,記得修改
                c.IncludeXmlComments(xmlModelPath);
            });

            #endregion

        }

 

3 在中間件代碼塊中添加 Swagger中間件

 

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// <summary>
        /// 配置中間件
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                #region Swagger
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
                });
                #endregion
            }


            app.UseMvc();
        }

 4.要配合我們第二步中的xml,我們要對webapi項目做如下操作

 右鍵webapi項目屬性——生成——勾選 XML文檔文件 如下圖:

如果引用了類庫項目 也要勾選類庫項目的XML文檔文件,然后被webapi項目引用。

 5.讓webapi啟動調試自動展示swagger接口信息頁面

上面4步完成后 要輸入 localhost:接口/swagger 這個地址才能看到接口信息頁面

為了默認啟動時 localhost:接口 頁面直接打開接口信息頁面 可以在 launchSettings.json 頁面進行配置

修改如下:

 大功告成!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM