.net core 使用swagger接口描述

 首先安装nuget包

Swashbuckle.AspNetCore.Swagger

Swashbuckle.AspNetCore.SwaggerGen

Swashbuckle.AspNetCore.SwaggerUI

1.在configureServices中 加入 swagger注册代码

 1    public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 4 
 5             services.AddSwaggerGen(c =>
 6             {
 7                 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
 8                 var xmlPath1 = System.IO.Path.Combine(AppContext.BaseDirectory, $"{xmlFile}");
 9 
10                 var xmlModelPath1 = System.IO.Path.Combine(AppContext.BaseDirectory, $"ClassLibrary1.xml");
11                 c.IncludeXmlComments(xmlPath1);
12                 c.IncludeXmlComments(xmlModelPath1);
13 
14                 c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
15                 {
16                     Title = "test", //根据项目修改
17                     Version = "V1",
18                     Contact = new Swashbuckle.AspNetCore.Swagger.Contact
19                     {
20                         Name = "test",
21                         Email = "234242@qq.com",
22                         Url = "https://www.test.com"
23                     },
24                     License = new License
25                     {
26                         Name = "内部授权",
27                         Url = "https://www.test.com"
28                     }
29                 });
30             });
31         }
ConfigureServices

2.在configure中  使用 swagger中间件

 1   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 2         {
 3             if (env.IsDevelopment())
 4             {
 5                 app.UseDeveloperExceptionPage();
 6             }
 7 
 8             app.UseMvc();
 9             //启用中间件服务生成Swagger作为JSON终结点
10             app.UseSwagger();
11             //启用中间件服务对swagger-ui,指定Swagger JSON终结点
12             app.UseSwaggerUI(c =>     //引用 Swashbuckle.AspNetCore.SwaggerUI
13             {
14                 c.SwaggerEndpoint("../swagger/v1/swagger.json", "O2O Order API");//SMS App API  根据内容修改 
15             });
16         }
Configure

为web项目及VModel项目生成XML文档

在接口上使用特性ProducesResponseType ,用以描述返回值信息。

 启动·项目 进入http://localhost:54022/swagger/index.html

IP port 改成你项目对应的ip 和 port

 点开刚才设置的post接口  即可查看到  参数和返回值信息了

 

原文地址:https://www.cnblogs.com/jasonbourne3/p/11210811.html