码迷,mamicode.com
首页 > Web开发 > 详细

DotnetCore之旅(2)---swagger的简单使用

时间:2019-05-17 00:16:29      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:bin   ring   extension   实现   containe   soft   cal   path   com   

swagger

swagger用于可视化api,并可实现对api格式化说明以及测试。

使用swagger

首先通过nuget引入Swashbuckle.AspNetCore(切记不是swagger)

技术图片

 

其次修改程序生成属性,分别配置程序生成路径和xml文档生成路径

技术图片

第三部修改startup类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Threading.Tasks;
 6 using Microsoft.AspNetCore.Builder;
 7 using Microsoft.AspNetCore.Hosting;
 8 using Microsoft.AspNetCore.Mvc;
 9 using Microsoft.Extensions.Configuration;
10 using Microsoft.Extensions.DependencyInjection;
11 using Microsoft.Extensions.Logging;
12 using Microsoft.Extensions.Options;
13 using Swashbuckle.AspNetCore.Swagger;
14 
15 namespace NetCoreExample
16 {
17     public class Startup
18     {
19         public Startup(IConfiguration configuration)
20         {
21             Configuration = configuration;
22         }
23 
24         public IConfiguration Configuration { get; }
25 
26         // This method gets called by the runtime. Use this method to add services to the container.
27         public void ConfigureServices(IServiceCollection services)
28         {
29             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
30             //添加SwaggerGen,配置api说明xml文档
31             services.AddSwaggerGen(p =>
32             {
33                 p.SwaggerDoc("v1",
34                     new Info { Title = "NetCoreExampleAPI", Version = "v1" }
35                     );
36                 string xmlPath = Path.Combine(AppContext.BaseDirectory, "NetCoreExample.xml"); //程序说明xml文档路径
37                 p.IncludeXmlComments(xmlPath);
38             });
39         }
40 
41         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
42         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
43         {
44             if (env.IsDevelopment())
45             {
46                 app.UseDeveloperExceptionPage();
47             }
48             app.UseMvc();
49 
50 
51             //注册swagger插件
52             app.UseSwagger();
53             app.UseSwaggerUI(p =>
54             {
55                 p.SwaggerEndpoint("/swagger/v1/swagger.json", "NetCoreExampleAPI V1");//注意v1是与AddSwaggerGen中指定的名称一致
56             });
57         }
58     }
59 }

 

最后运行后访问http://localhost:5000/swagger/index.html

技术图片

 

附:当然也可以配置多个api说明文档,不一定是程序本身的api说明。需确认xml文档正确有效,即可配置。以上是针对项目本身进行简单配置。如果需要其他的配置,请参照swagger官网

 

DotnetCore之旅(2)---swagger的简单使用

标签:bin   ring   extension   实现   containe   soft   cal   path   com   

原文地址:https://www.cnblogs.com/johnyong/p/10878886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!