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

系列文章

  1. .Net Core 分佈式微服務框架介紹 - Jimu
  2. .Net Core 分佈式微服務框架 - Jimu 添加 Swagger 支持

1、前言

最近有空就優化 Jimu (一個基於.Net Core 的分佈式微服務框架),考慮到如今的開發組織都向先後端分離發展,先後端各司其職,好的 api 文檔能夠減小你們溝通的時間成本,因此優先給 Jimu 添加對 api 文檔生成的支持。市面上很是著名和牛逼的的 api 文檔生成框架非 swagger 莫屬。 它能夠用來生成、描述、調用可視化的 Web 服務。花了 二天多的時間把它集成到 Jimu 的 apigateway。html

如圖git

api 列表
github

api 明細
後端

2、使用方式

1. 環境

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

2. 添加引用

Install-Package Jimu.Client.ApiGateway.SwaggerIntegration

3. 啓動代碼

在 Startup 裏添加 UseJimuSwagger()api

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

4. 定義接口(服務/方法)

接口定義能夠添加三種標註,這些標註最終會顯示在 swagger 生成的文檔。bash

a. JimuService 標註是對接口元數據的定義和描述,如建立人、時間、描述、訪問角色限制等。
b. JimuFieldComment 標註是對形式參數的註釋。
c. JimuReturnComment 標註是對接口的返回類型作註釋。app

[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; }

    }

3、圖解

4、總結

支持開源是很累和很耗時間的活,不過開源過程當中本身也學到不少知識,但願能夠一直堅持下去。前後端分離

5、源碼

https://github.com/grissomlau/jimu分佈式

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

相關文章
相關標籤/搜索