在解决方案中添加一个.netcore类库子项目,命名为Test.Model,用于存放API接口的输入输出参数类
using System;
using System.Collections.Generic;
using System.Text;
namespace Test.Model.InputParam
{
public class SearchInput
{
///
/// 姓名
///
public string name { get; set; }
///
/// 性别
///
public string sex { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Test.Model.OutputParam
{
public class SearchOutput
{
///
/// 用户ID
///
public int UserId { get; set; }
///
/// 姓名
///
public string UserName { get; set; }
///
/// 性别
///
public string Sex { get; set; }
///
/// 年龄
///
public int Age { get; set; }
///
/// 注册时间
///
public DateTime CreateTime { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Test.Model.InputParam;
using Test.Model.OutputParam;
namespace Test.Web.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
///
/// 查询用户
///
///
///
[HttpGet]
public List UserSearch(SearchInput input)
{
//逻辑暂空,这里主要看生成的输入输出
return null;
}
}
}
至此,准备工作已经差不多了,项目结构如下:
这里不使用自动生成的/swagger/,而是自己添加方便定制
右键wwwroot,添加一个html页面,内容如下:
swagger
打开Test.Web项目下的Properties/launchSettings.json文件,launchUrl属性值配置为:Index.html
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "API",
Description = "api文档",
TermsOfService = "None"
});
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "Test.Web.xml");
var xmlPathByModel = Path.Combine(basePath, "Test.Model.xml");
options.IncludeXmlComments(xmlPathByModel);
//true表示生成控制器描述,包含true的IncludeXmlComments重载应放在最后,或者两句都使用true
options.IncludeXmlComments(xmlPath,true);
});
app.UseStaticFiles();//启用默认文件夹wwwroot
app.UseSwagger();
app.UseSwaggerUI(action =>
{
action.ShowExtensions();
action.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
});
到此,文档已经生成了,如图:
点击对应的Model即可查看输入输出参数注释说明。
webapi经常碰到接口需要验证token的情况,使用Try it out测试时候怎么提交Token呢
public class AddAuthTokenHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
{
operation.Parameters = new List();
}
var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;
//先判断是否是匿名访问,
var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
//非匿名的方法,链接中添加accesstoken值
if (!isAnonymous)
{
operation.Parameters.Add(new NonBodyParameter()
{
Name = "token",
In = "query",//query header body path formData
Type = "string",
Required = true //是否必选
});
}
}
}
}
options.OperationFilter();
完整的StartUp.cs文件如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Test.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "API",
Description = "api文档",
TermsOfService = "None"
});
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "Test.Web.xml");
var xmlPathByModel = Path.Combine(basePath, "Test.Model.xml");
options.IncludeXmlComments(xmlPathByModel);
//true表示生成控制器描述,包含true的IncludeXmlComments重载应放在最后,或者两句都使用true
options.IncludeXmlComments(xmlPath,true);
options.OperationFilter();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseStaticFiles();//启用默认文件夹wwwroot
app.UseSwagger();
app.UseSwaggerUI(action =>
{
action.ShowExtensions();
action.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
});
}
}
///
/// 添加Token参数
///
public class AddAuthTokenHeaderParameter : IOperationFilter
{
///
/// 非匿名方法添加Token参数
///
///
///
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
{
operation.Parameters = new List();
}
var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;
//先判断是否是匿名访问,
var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
//非匿名的方法,链接中添加accesstoken值
if (!isAnonymous)
{
operation.Parameters.Add(new NonBodyParameter()
{
Name = "token",
In = "query",//query header body path formData
Type = "string",
Required = true //是否必选
});
}
}
}
}
}
生成的文档最终效果,点击Try it out 以后会生成一个填写Token的输入框: