zoukankan      html  css  js  c++  java
  • ASP.NET Core Web API中使用Swagger


    本节导航

    • Swagger介绍
    • 在ASP.NET CORE 中的使用swagger

      在软件开发中,管理和测试API是一件重要而富有挑战性的工作。在我之前的文章《研发团队,请管好你的API文档》 也专门阐述了通过文档管理工具,来保证API文档和代码的一致性,这样更加有助于团队的协作。

      以往我们总是通过第三方平台工具来管理我们的API文档,如eolinker。在测试方面,我们也会依赖fiddler,PostMan这样的工具。

      Swagger兼具了API文档管理和测试的功能,而且保证了代码和文档的一致性。它提供了无需任何实现逻辑的RESTfulAPI的UI表示。它允许用户在没有任何代码访问的情况下了解服务的功能,并减少创建服务文档的时间。

    1 Swagger介绍

      Swagger兼具了API文档管理和测试的功能,而且保证了代码和文档的一致性。它提供了无需任何实现逻辑的RESTfulAPI的UI表示。它允许用户在没有任何代码访问的情况下了解服务的功能,并减少创建服务文档的时间。

      swagger使用swagger工具基于我们编写的服务代码生成的swagger.json文件来生成文档管理界面。此文件描述服务的功能,即服务支持多少方法,并提供有关方法参数的信息。使用这个文件,SwaggerUI生成客户机代码。下面是swagger.json文件的一个示例。

    {
    	"swagger": "2.0",
    	"info": {
    		"version": "1.0",
    		"title": "My Demo API"
    	},
    	"paths": {
    		"/api/Values": {
    			"get": {
    				"tags": ["Values"],
    				"summary": "Get values",
    				"operationId": "Get",
    				"consumes": [],
    				"produces": ["text/plain", "application/json", "text/json"],
    				"parameters": [],
    				"responses": {
    					"200": {
    						"description": "Success",
    						"schema": {
    							"uniqueItems": false,
    							"type": "array",
    							"items": {
    								"type": "string"
    							}
    						}
    					}
    				}
    			},
    			"post": {
    				"tags": ["Values"],
    				"operationId": "Post",
    				"consumes": ["application/json-patch+json", "application/json", "text/json", "application/*+json"],
    				"produces": [],
    				"parameters": [{
    					"name": "value",
    					"in": "body",
    					"required": false,
    					"schema": {
    						"type": "string"
    					}
    				}],
    				"responses": {
    					"200": {
    						"description": "Success"
    					}
    				}
    			}
    		}
    	},
    	"definitions": {}
    }
    
    

      在APS.NET Core Web API 中,我们可以用Swashbuckle.AspNetCoreNSwag这两个包来实现Swagger,而且二者都是github上开源的。此外,nswag还提供了生成typescript客户端代码的方法以及用于API的服务代码。

    1.2 TPL

      任务并行库(TPL)是System.Threading和System.Threading.Tasks命名空间中的一组公共类型和API。

      TPL动态地扩展并发度,以最有效地使用所有可用的处理器。通过使用TPL,您可以最大限度地提高代码的性能,同时专注于您的代码的业务实现。

      从.NET Framework 4开始,TPL是编写多线程和并行代码的首选方式。

    2 在ASP.NET CORE 中的使用swagger

      这里以Swashbuckle.AspNetCore来实现。

      以下是在ASP.net Core Web API中配置Swagger的步骤:

    1. 安装Swashbuckle.AspNetCore

    PM> Install-Package Swashbuckle.AspNetCore

    2. 配置swagger中间件

      要将swagger middle添加到请求管道,需要在startup类的configureService方法中添加swaggergen方法。在这里,我们可以定义一个或多个swagger XML文档。

    Startup.cs

    // 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_2);
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1.0", new Info { Title = "My Demo API", Version = "1.0" });
                    c.IncludeXmlComments(System.IO.Path.Combine(System.AppContext.BaseDirectory, "ZhiKeCore.API.xml"));
                });
            }
    

      如果要启用这个中间件,我们还需要在startup类的configure方法中调用useswagger方法。在这里,我们还需要配置swagerendpoint来生成UI。useswagegrui将添加一个静态文件中间件来加载swager.json文件。

    // 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.UseHttpsRedirection();
                app.UseMvc();
    
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My Demo API (V 1.0)");
                });
            }
    
    

      以上是配置swagger的基本步骤,如果我们想使用Visual Studio在开发环境中启动Swagger,还需要做一点设置。选择项目-属性-Debug,修改启动浏览器(Launch Browser)的值为swagger。

    使用场景

      当我们启动程序以后,可以看到如下界面:

    使用场景

      正如我们在这里看到的,它对每个HTTP动词使用不同的颜色代码。当我们单击任何操作方法时,它将询问参数详细信息,当我们单击“非常”按钮时,它将向Web API发送请求。

      在测试我们的WebAPI时,Swagger只需要最少的配置即可。

      那么,如果我们想要在UI上显示代码注释应该怎么办呢?

      在.NET Core中,我们可以通过在项目属性窗口的“构建”选项卡下设置“XML文档文件”属性来获取XML注释。

    使用场景

      默认情况下,Swagger UI不显示此文档。我们需要传递包含exmlcomments的路径。

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
           // 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_2);
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1.0", new Info { Title = "My Demo API", Version = "1.0" });
                    c.IncludeXmlComments(System.IO.Path.Combine(System.AppContext.BaseDirectory, "ZhiKeCore.API.xml"));
                });
            }
    
    

    使用场景

    参考

    关注
      请关注微信公众号智客坊

    使用场景

  • 相关阅读:
    ATOM编辑器插件
    说说关于IE浏览器兼容性
    git命令
    Vue js 的生命周期详解
    Flexbox 布局教程
    到底vuex是什么?
    CSS3 动画 animation和@keyframes
    zabbix添加触发器Triggers
    zabbix邮件报警
    修改zabbix监控项刷新时间
  • 原文地址:https://www.cnblogs.com/lucky_hu/p/11130209.html
Copyright © 2011-2022 走看看