Net Core3.1 add Swagger

First, why use Swagger

With the development of Internet technology, now the basic architecture of the site are from the original back-end rendering, it becomes: front-end rendering, isolated form the backend, and front-end technology and back-end technology on their way farther and farther. 

The only link front and rear, into the API interface; API documentation into a link to contact the front and back end developers, is becoming increasingly important, swagger that makes you a better framework for writing API documentation.

Before no API documentation tools, we are a handwritten API documentation, somewhere has written, there is writing on the confluence, there is on readme.md project directory under the corresponding write, every company has every the company's games are played, neither good nor bad.

Writing API documentation tools are numerous, but can be called a "framework", estimated only a swagger.

Second, the service configuration Swagger

1, API project to build a net Core 3.1, and does not demonstrate the will

2, a reference packet Nuget

Right-project dependencies -> Management Nuget package -> Browse -> Search "Swashbuckle.AspNetCore" -> Install to install the latest version 

 

After the installation is complete to see Swagger just introduced in Nuget dependent projects in

 

 

 

 

3, configuration services

Open Startup.cs class, method editing ConfigureServices

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            #region swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
            });
            #endregion
        }

 

3, start Http middleware

Edit Configure Methods

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //判断是否是环境变量
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

 

4, to see the effect

To which has been added to complete the swagger, F5 to run the debugger, following the domain name input / swagger, for example: http: // localhost: 54067 / swagger / index.html hit enter, it came out

 

 

 

 

5, set the default home page to access directly - the production environment

Every manual input / swagger in the domain name back, a lot of trouble! 

swagger provided us with this extension, we can specify a null character as the address of swagger, the configuration of middleware in Configure:

           #region swagger 
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

                c.RoutePrefix = "";//路径配置,设置为空,表示直接访问该文件,表示直接在根域名(localhost:8001)访问该文件
                //这个时候去launchSettings.json中把"launchUrl": "swagger/index.html"去掉, 然后直接访问localhost:8001/index.html即可        
            });
            #endregion

然后再把我们上边的项目文件 launchSettings.json 的 launchUrl 给去掉就行了,这样我们无论是本地开发环境,还是生产环境,都可以默认首页加载了。

 

这时候会发现没有注释,如果有注释可读性就很好了,下面开始实现注释

6、显示注释

 1、给接口加一个注释

        /// <summary>
        /// ID 获取Json列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public IEnumerable<WeatherForecast> Get(int id)    

2、右键点击项目---->属性------>生成------>勾选xml文档文件

 

 

3、在startup类中的ConfigureServices 方法中的服务集合中添加如下代码

            #region swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
                
                var basePath = AppContext.BaseDirectory;

                var xmlPath = Path.Combine(basePath, "Blog.Core.xml");
                c.IncludeXmlComments(xmlPath, true); //添加控制器层注释(true表示显示控制器注释)
            });
            #endregion

4、运行项目并访问swaggerUI

 

 可以显示注释了

 

7、对 Model 也添加注释说明

新建一个.net core 类库Blog.Core.Model,注意是 .net core的类库,或者使用标准库也是可以的!(标准库可以在 NetCore 和 Framework 两个项目都可以跑)

 

 

然后新建一个model

    /// <summary>
    /// 这是爱
    /// </summary>
    public class Love
    {
        /// <summary>
        /// id
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
    }

1、当前 api 层直接引用了 Blog.Core.Model 层;

 

2、Blog.Core.Model 右键属性配置 xml

 

 3、导入model.xml到swagger

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            #region swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
                
                var basePath = AppContext.BaseDirectory;

                var xmlPath = Path.Combine(basePath, "Blog.Core.xml");
                c.IncludeXmlComments(xmlPath, true); //添加控制器层注释(true表示显示控制器注释)

                var xmlModelPath = Path.Combine(basePath, "Blog.Core.Model.xml");
                c.IncludeXmlComments(xmlModelPath, true);
            });
            #endregion
        }

 

接口添加注释

        /// <summary>
        /// post
        /// </summary>
        /// <param name="love">model 实体类</param>
        [HttpPost]
        public void Post(Love love)
        { 
            
        }

重新运行就出来了

 

 

 

 

8、隐藏某些接口

如果不想显示某些接口,直接在controller 上,或者action 上,增加特性

[ApiExplorerSettings(IgnoreApi = true)]

        /// <summary>
        /// post
        /// </summary>
        /// <param name="love">model 实体类</param>
        [HttpPost]
        [ApiExplorerSettings(IgnoreApi =true)]
        public void Post(Love love)
        { 
            
        }    

Post方法就不显示了

 

 

三、结语

下一篇 Swagger JWT 权限,给接口加权限验证

Guess you like

Origin www.cnblogs.com/shuaichao/p/12374967.html