当前位置: 移动技术网 > IT编程>软件设计>领域驱动 > ABP项目中使用Swagger生成动态WebAPI

ABP项目中使用Swagger生成动态WebAPI

2018年01月15日  | 移动技术网IT编程  | 我要评论

本文是根据角落的白板报的《使用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中。

 1 public void ConfigureSwaggerUI()
 2 {
 3     Configuration.Modules.AbpWebApi().HttpConfiguration
 4         .EnableSwagger(c =>
 5         {
 6             c.SingleApiVersion("v1", "DemoAPI文档");
 7             c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
 8 
 9             //将application层中的注释添加到SwaggerUI中
10             var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
11 
12             var commentsFileName = "Bin//Demo.Application.xml";
13             var commentsFile = Path.Combine(baseDirectory, commentsFileName);
14             //将注释的XML文档添加到SwaggerUI中
15             c.IncludeXmlComments(commentsFile);
16         })
17         .EnableSwaggerUi();
18 }

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

UpdateRolePermissionsInput.cs

/// <summary>
/// 修改角色权限信息接收的DTO
/// </summary>
public class UpdateRolePermissionsInput
{
    /// <summary>
    /// 角色ID
    /// </summary>
    [Range(1, 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

 

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网