首页 技术 正文
技术 2022年11月7日
0 收藏 570 点赞 484 浏览 5133 个字

本文是根据角落的白板报的《使用ABP实现SwaggerUI,生成动态webapi》一文的学习总结,感谢原文作者角落的白板报

1 安装Swashbuckle.core

1.1 选择WebApi项目,右键“管理NuGet程序包”。

1.2 输入 “Swashbuckle.core”,搜索。选择Swashbuckle.core,右边点击安装。

2 配置Swashbuckle

2.1 打开WebApi项目中的DemoWebApiModule.cs文件。创建ConfigureSwaggerUI()方法,并在Initialize()中调用。

public void ConfigureSwaggerUI(){    Configuration.Modules.AbpWebApi().HttpConfiguration        .EnableSwagger(c =>        {            c.SingleApiVersion("v1", "DemoAPI文档");            c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());        })        .EnableSwaggerUi();}
public override void Initialize(){    IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());    Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder        .ForAll<IApplicationService>(typeof(DemoApplicationModule).Assembly, "app")        .Build();    Configuration.Modules.AbpWebApi().HttpConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));    ConfigureSwaggerUI();}

2.2 运行项目。

运行项目,打开地址“/swagger/ui/index”,即可查看WebApi。

3 增强WebApi文档

3.1 打开Application项目的属性设置,勾选“XML文档文件”。

3.2 将application层中的注释添加到SwaggerUI中。

 public void ConfigureSwaggerUI() {     Configuration.Modules.AbpWebApi().HttpConfiguration         .EnableSwagger(c =>         {             c.SingleApiVersion("v1", "DemoAPI文档");             c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());             //将application层中的注释添加到SwaggerUI中             var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;             var commentsFileName = "Bin//Demo.Application.xml";             var commentsFile = Path.Combine(baseDirectory, commentsFileName);             //将注释的XML文档添加到SwaggerUI中             c.IncludeXmlComments(commentsFile);         })         .EnableSwaggerUi(); }

3.3 在API接口方法中添加注释后,SwaggerUI就会显示对应的注释信息。以Role为例,添加注释如下:

UpdateRolePermissionsInput.cs

/// <summary>/// 修改角色权限信息接收的DTO/// </summary>public class UpdateRolePermissionsInput{    /// <summary>    /// 角色ID    /// </summary>    [Range(, int.MaxValue)]    public int RoleId { get; set; }    /// <summary>    /// 获取权限名称列表    /// </summary>    [Required]    public List<string> GrantedPermissionNames { get; set; }}

IRoleAppService.cs

/// <summary>/// 角色信息接口/// </summary>public interface IRoleAppService : IApplicationService{    /// <summary>    /// 修改角色的权限信息    /// </summary>    /// <param name="input"></param>    /// <returns></returns>    Task UpdateRolePermissions(UpdateRolePermissionsInput input);}

3.4 再次运行项目,可以看到WebApi文档出现了注释信息。

4 修改访问方式

4.1 使用EnableSwaggerUi的重载方法。

SwaggerUI默认使用的是EnableSwaggerUi()方法,访问路径默认为“/swagger/ui/index/”。 F12转到定义,我们可以看到EnableSwaggerUi有一个重载方法。

public void EnableSwaggerUi(Action<SwaggerUiConfig> configure = null);public void EnableSwaggerUi(string routeTemplate, Action<SwaggerUiConfig> configure = null);

ConfigureSwaggerUI中更改EnableSwaggerUi()为:

EnableSwaggerUi("apis/{*assetPath}");

4.2 更改后的访问路径变为”apis/index”,运行程序,查看。

5 界面优化

5.1 调整界面CSS样式

(1)新建style.css样式文件,可以自定义文件名。

(2)style.css中编辑样式脚本,以下为示例:

.swagger-section #header {    background-color: #ff6a00;    padding: 14px;}

(3)style.css文件属性设置为“嵌入的资源”。   非常重要!!!

(4)修改ConfigureSwaggerUI方法。

EnableSwaggerUi("apis/{*assetPath}", c=>        {            c.InjectStylesheet(Assembly.GetExecutingAssembly(),                "Demo.SwaggerUI.css.style.css");        });

其中,Demo为项目命名空间,Demo以后的为文件夹或文件。

(5)预览效果,可以看到header背景色由默认的绿色改为了橙色。

5.2 汉化

操作与5.1相似。

(1)新建swagger.js文件,可以自定义文件名。

(2)编辑swagger.js。

$(function () {    $("#logo").text("Demo");    $("#logo").attr("href", "http://www.Demo.com");    $("#explore").text("查询");    $(".options .toggleEndpointList").each(function () {        $(this).text("展开/隐藏");    });    $(".options .collapseResource").each(function () {        $(this).text("显示资源列表");    });    $(".options .expandResource").each(function () {        $(this).text("显示资源明细");    });    $(".operations .description-link").each(function () {        $(this).text("实体模型");    });    $(".operations .snippet-link").each(function () {        $(this).text("实体类型");    });    $(".operations .response-content-type label").each(function () {        $(this).text("请求方式");    });    $(".operations .sandbox h4").each(function () {        $(this).text("参数列表");    });    $(".operations .response_hider").each(function () {        $(this).text("隐藏响应界面");    });    $(".operations .response .curl").each(function () {        $(this).text("请求头");    });    $(".operations .response .curl").each(function () {        $(this).next().text("请求路径");    });    $(".response_body").each(function () {        $(this).prev().text("响应正文");    });    $("[class='block response_code']").each(function () {        $(this).prev().text("响应代码");    });    $("[class='block response_headers']").each(function () {        $(this).prev().text("响应标头");    });    $(".parameter-content-type div label").each(function () {        $(this).text("参数的内容类型︰");    });    $("small.notice").each(function () {        $(this).text("单击要设置为参数值");    });    $(".body-textarea").each(function () {        var op = $(this).attr("placeholder");        if (op === "(required)") {            $(this).attr("placeholder", "(不可为空)");        }    });    $(".body-textarea required");    $(".fullwidth thead tr th").each(function () {        var key = $(this).text();        switch (key) {            case "Parameter":                $(this).text("参数名");                break;            case "Value":                $(this).text("参数值");                break;            case "Description":                $(this).text("描述");                break;            case "Parameter Type":                $(this).text("参数类型");                break;            case "Data Type":                $(this).text("数据类型");                break;            default:                break;        }    });    $("input[type='submit']").val("测试");})

其中,logo换成了文字“Demo”,logo的链接换成了“http://www.Demo.com”。可根据实际修改。

(3)swagger.js文件属性设置为“嵌入的资源”。

(4)修改ConfigureSwaggerUI方法。

EnableSwaggerUi("apis/{*assetPath}", c=>        {            c.InjectStylesheet(Assembly.GetExecutingAssembly(),                "Demo.SwaggerUI.css.style.css");            c.InjectJavaScript(Assembly.GetExecutingAssembly(),                "Demo.SwaggerUI.script.swagger.js");        });

其中,Demo为项目命名空间,Demo以后的为文件夹或文件。

(5)预览效果。

后记:

在整个过程中,我遇到的问题是,css文件和js文件设置未生效。琢磨了很久,根本原因是未设置文件属性为“嵌入的资源”!牢记这一步!

本节源码链接:http://pan.baidu.com/s/1nuZHJvz 密码:a0tu

 
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902