.Net Core 分布式微服务框架 - Jimu 添加 Swagger 支持

系列文章

  1. .Net Core 分布式微服务框架介绍 - Jimu
  2. .Net Core 分布式微服务框架 - Jimu 添加 Swagger 支持

一、前言

最近有空就优化 Jimu (一个基于.Net Core 的分布式微服务框架),考虑到现在的开发组织都向前后端分离发展,前后端各司其职,好的 api 文档可以减少大家沟通的时间成本,所以优先给 Jimu 添加对 api 文档生成的支持。市面上非常著名和牛逼的的 api 文档生成框架非 swagger 莫属。 它可以用来生成、描述、调用可视化的 Web 服务。花了 二天多的时间把它集成到 Jimu 的 apigateway。

如图

api 列表

api 明细

二、使用方式

1. 环境

  • Net Core 2.0
  • 基于Jimu 框架的 ApiGateway

2. 添加引用


Install-Package Jimu.Client.ApiGateway.SwaggerIntegration

3. 启动代码

在 Startup 里添加 UseJimuSwagger()


        public void ConfigureServices(IServiceCollection services)
        { 
            services.UseJimuSwagger(); // 添加 Swagger 支持 
        }
 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {  
            app.UseJimuSwagger(); // 添加 Swagger 支持

     

4. 定义接口(服务/方法)

接口定义可以添加三种标注,这些标注最终会显示在 swagger 生成的文档。

a. JimuService 标注是对接口元数据的定义和描述,如创建人、时间、描述、访问角色限制等。
b. JimuFieldComment 标注是对形式参数的注释。
c. JimuReturnComment 标注是对接口的返回类型做注释。


        [JimuService(EnableAuthorization = true, CreatedBy = "grissom", CreatedDate = "2018-07-17", Comment = "根据新闻 id 获取新闻内容")]
        [JimuFieldComment("id", "新闻id")]
        [JimuReturnComment("一篇新闻内容")]
        News GetNews(string id);

5. 定义对象 (DTO)

如果接口参数或返回类型是一个用户定义的类,对应的属性也可以添加注释标注 JimuFieldComment, 这些标注最终会显示在 swagger 生成的文档。

    public class News
    {
        [JimuFieldComment("新闻id")]
        public string Id { get; set; }
        [JimuFieldComment("新闻标题")]
        public string Title { get; set; }
        [JimuFieldComment("作者")]
        public string Director { get; set; }
        [JimuFieldComment("发布时间")]
        public string PostTime { get; set; }
        [JimuFieldComment("新闻内容")]
        public string Content { get; set; }

    }

三、图解

四、总结

支持开源是很累和很耗时间的活,不过开源过程中自己也学到很多知识,希望可以一直坚持下去。

五、源码

https://github.com/grissomlau/jimu

https://github.com/grissomlau/jimu.demo

posted @ 2018-08-07 11:11  Grissom007  阅读(4026)  评论(6编辑  收藏  举报