循序渐进学.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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
  "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的调试了。 

 

posted @ 2019-06-26 16:54  奋斗的中年人哈哈哈  阅读(296)  评论(0)    收藏  举报