利用Swagger调试WebApi

1 本篇概述

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

2 使用NuGet获取包

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

3 添加代码

  在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");
    });
}

4 配置

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

使用场景

5 启动

  启动项目,浏览器输入: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的调试了。

使用场景

版权声明: 本文为智客工坊「seabluescn」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

results matching ""

    No results matching ""