循序渐进学.Net Core Web Api开发系列【2】:利用Swagger调试WebApi


系列目录

循序渐进学.Net Core Web Api开发系列目录

 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi

 

一、概述

既然前后端开发完全分离,那么接口的测试和文档就显得非常重要,文档维护是一件比较麻烦的事情,特别是变更的文档,这时采用Swagger就会非常方便,同时解决了测试和接口文档两个问题。

 

二、使用NuGet获取包

使用NuGet搜索包:Swashbuckle.aspnetcore并安装。

 

三、添加代码

在Startup类的ConfigureServices方法内添加下面代码(加粗部分)

      public void ConfigureServices(IServiceCollection services)
        {
           services.AddMvc();
           
            services.AddSwaggerGen(option => { option.SwaggerDoc("v1", new Info { Version = "v1", Title = "SaleService接口文档", Description = "RESTful API for SaleService.", TermsOfService = "None", Contact = new Contact { Name = "seabluescn", Email = "seabluescn@163.com", Url = "" } }); //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "SaleService.xml"); option.IncludeXmlComments(xmlPath); });
        }

在Startup类的Configure方法内添加下面代码(加粗部分)

       public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {   
            app.UseMvcWithDefaultRoute();

            app.UseSwagger(); app.UseSwaggerUI(option => { option.ShowExtensions(); option.SwaggerEndpoint("/swagger/v1/swagger.json", "SaleService V1"); });
        }

 

四、配置

需要在生成配置选项内勾选XML文档文件,项目编译时会生成该文件。Debug和Release模式都设置一下。否则会报一个System.IO.FileNotFoundException的错误。

 

五、启动

 启动项目,浏览器输入:http://localhost:50793/swagger/ 即可。

也可以修改launchsettings.json文件,默认项目启动时运行swagger

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:50792/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SaleService": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:50793/"
    }
  }}

如果你对你的控制器方法进行了注释,swagger接口页面就会体现出来。

        /// <summary>
        /// 根据产品编号查询产品信息 /// </summary>
        /// <param name="code">产品编码</param>
        /// <returns>产品信息</returns>
        [HttpGet("{code}")]  
        public Product GetProduct(String code)
        {
            var product = new Product
            {
                ProductCode = code,
                ProductName = "啫喱水"
            };

            return product;
        }

 

下面为Swagger的首页:可以用它进行API的调试了。 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM