Abp Vnext手动搭建简单项目系列5
添加Swagger接口文档
源码:https://github.com/1259724620/hqh.project20200501.git
一、web项目添加swagger包Swashbuckle.AspNetCore
二、在Web项目模块类WebModule.cs文件添加如下代码
三、在web项目新建文件夹swagger并添加如下几个类
/// <summary> /// 枚举参数示例 /// </summary> public class EnumSchemaFilter : ISchemaFilter { /// <summary> /// 设置枚举显示 /// </summary> /// <param name="schema"></param> /// <param name="context"></param> public void Apply(OpenApiSchema schema, SchemaFilterContext context) { var enumType = context.Type.GetNonNullableType(); if (enumType.IsEnum) { var extensions = new Dictionary<string, IOpenApiExtension>(); foreach (Enum value in Enum.GetValues(enumType)) { var display = value.DisplayName(); extensions.Add(Convert.ToInt32(value).ToString("G"), new OpenApiString(string.IsNullOrWhiteSpace(display) ? "" : ":" + display)); } schema.Extensions = extensions; if (string.IsNullOrWhiteSpace(schema.Description)) { schema.Description = enumType.DisplayDescription(); } } } }
/// <summary> /// 隐藏Swagger Api特性 /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class SwaggerIgnoreAttribute : Attribute { }
/// <summary> /// Swagger Api 过滤器 /// </summary> public class SwaggerIgnoreFilter : IDocumentFilter { /// <summary> /// /// </summary> /// <param name="swaggerDoc"></param> /// <param name="context"></param> public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var ignoreApis = context.ApiDescriptions.Where(m => m.RelativePath.StartsWith("Abp") || m.RelativePath.StartsWith("api/abp") || (m.TryGetMethodInfo(out MethodInfo methodInfo) && methodInfo.CustomAttributes.Any(info => info.AttributeType == typeof(SwaggerIgnoreAttribute)))); if (ignoreApis != null) { foreach (var ignoreApi in ignoreApis) { swaggerDoc.Paths.Remove("/" + ignoreApi.RelativePath); } } } }
四、修改controller下面的控制器
新建一个BaseController,如下代码,记得添加路由标记属性,否则swagger不会显示
/// <summary> /// 基础控制器 /// </summary> [Route("v1/api/[controller]")] public class BaseController: AbpController { }
修改UserController,HomeController继承为BaseController,如下
/// <summary> /// 用户控制器 /// </summary> public class UserController : BaseController { /// <summary> ///新增或编辑用户 /// </summary> /// <returns></returns> [HttpPost("AddEditUser")] public async Task<Result> AddEditUser([FromBody]AddEditUserDto input, [FromServices]IUserService service) { return await service.AddEditUser(input); } }
public class HomeController: BaseController { /// <summary> /// /// </summary> /// <returns></returns> public IActionResult Index() { return Redirect("~/swagger"); } }
五、设置web项目,dto项目,service项目属性
选中项目-->属性-->生成,然后如下栏位勾选保存即可
六、运行,如下,并调用接口成功
相关推荐
xxuncle 2020-07-04
唐宋源码清 2020-03-03
朱建伟 2020-01-16
yisimo 2019-07-01
zwq 2015-02-06
宜家软件 2019-04-01
一个心理学实践者的旅程 2018-04-01
优主张 2018-02-11
插画家出列 2018-02-11
深圳湾 2018-02-09
BitTigerio 2018-01-30
安在信息安全新媒体 2018-01-24
前端外刊评论 2018-01-13
学习编程 2017-12-30
OccamsRazor 2017-12-29
BitTigerio 2017-12-27
软件设计 2017-07-21
BAT 批处理程序 2017-05-05