上一步我们创建好CoreApi
接下来在框架中加入 Swagger 并发布 到 IIS
(1)首先点击依赖项》管理Nuget包
(2)输入 Swashbuckle.aspnetCore 比如:
图中两个Swagger 插件需要我们安装 注意:我这里已经安装过显示的是 卸载
(3) 在框架中 添加Swagger 注解的帮助类 HttpHeaderOperation 下面是我完整的.CS文件
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; //添加引用 using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.AspNetCore.Authorization; namespace WebCoreApi { public class HttpHeaderOperation : IOperationFilter { /// <summary> /// 实现接口 /// </summary> /// <param name="operation"></param> /// <param name="context"></param> public void Apply(Operation operation, OperationFilterContext context) { if (operation.Parameters == null) { operation.Parameters = new List<IParameter>(); } var actionAttrs = context.ApiDescription.ActionAttributes(); var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); if (isAuthorized == false) //提供action都没有权限特性标记,检查控制器有没有 { var controllerAttrs = context.ApiDescription.ControllerAttributes(); isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); } var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); if (isAuthorized && isAllowAnonymous == false) { operation.Parameters.Add(new NonBodyParameter() { Name = "Authorization", //添加Authorization头部参数 In = "header", Type = "string", Required = false }); } } } }
(4) 添加 Swagger 的·服务方法 在 Startup中的 ConfigureServices方法里
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new Info { Version = "v1", //版本号 Title = "Szl接口文档", //标题 Description = "RESTful API ", TermsOfService = "",//服务的条件 //第一个参数Name 创建人名称/也可以是 负责人名称 第二个参数 联系邮箱 Contact = new Contact { Name = "Su", Email = "szl_0000@126.com", Url = "北京" } }); //获取设置配置信息的 的路径对象 swagger界面配置 var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "AspNetCoreApiSwagger.xml"); x.IncludeXmlComments(xmlPath); x.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数 }); }