iT邦幫忙

2021 iThome 鐵人賽

1
自我挑戰組

.NET Core WebApi網頁應用開發系列 第 22

.Net Core Web Api_筆記22_Swagger自訂文件並讀取API註解描述

Swagger剛開始可以將其理解成網頁版本的postman

我們可以對其測試發送資料看回傳結果

在預設webapi專案產生的WeatherForecastController
新增一個post action

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyNet5ApiAdoTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPost("Add")]
        public string AddWeatherForecast(WeatherForecast weather)
        {
            if(weather != null)
            {
                DateTime dt = weather.Date;
                string summary = weather.Summary;
                int TemperatureC = weather.TemperatureC;
                int TemperatureF = weather.TemperatureF;
                return "1";
            }
            return "0";
        }



    }
}

在此準備一份json 測試資料嘗試post

{
   "date":"2022-06-09T09:49:03.3956842+08:00",
   "temperatureC":9,
   "temperatureF":47,
   "summary":"Hot"
}

https://ithelp.ithome.com.tw/upload/images/20220110/201074526SjpUrv974.png

https://ithelp.ithome.com.tw/upload/images/20220110/20107452A5ZPtJgctr.png

在專案中下中斷點

https://ithelp.ithome.com.tw/upload/images/20220110/20107452yh47oAOH3e.png

下方則會呈現回應結果與curl對應呼叫語法轉譯
https://ithelp.ithome.com.tw/upload/images/20220110/20107452hs6vUg9i58.png

而在Swagger中若我們想自訂API文檔給其他外部開發者或廠商去做使用
移至我們的Startup.cs的ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerDocument(config => {
        config.PostProcess = document =>
        {
            //API版號
            document.Info.Version = "v1.0.1";
            //API名稱
            document.Info.Title = "廠房MES API 測試";
            //API描述介紹
            document.Info.Description = "提供原物料資料查詢存取";
            //API聯絡人資訊
            document.Info.Contact = new NSwag.OpenApiContact
            {
                Name = "XXX科技",
                Email = "ppap@outlook.com",
                Url = "https://#"
            };
            //API授權許可資訊
            document.Info.License = new NSwag.OpenApiLicense
            {
                Name = "XXX科技 版權所有",
                Url = "https://#"
            };
        };
    });//註冊NSwag提供的服務
}

https://ithelp.ithome.com.tw/upload/images/20220110/20107452M7DqTYrHXc.png

而一般API官方文件也會習慣寫中英文的註解描述各隻API功能
在C#專案我們都知道可透過XML在每個函數、method上方添加功能描述註解

https://ithelp.ithome.com.tw/upload/images/20220110/201074524O5xKw6c97.png

若寫好的API這樣子呈現別人會不曉得功能與目的

https://ithelp.ithome.com.tw/upload/images/20220110/20107452EQ6OlnMzCG.png

由於預設專案是不會開啟產生XML註解並讀取機制的
因此要自己去開啟

https://ithelp.ithome.com.tw/upload/images/20220110/201074529GL3xi2JNO.png

https://ithelp.ithome.com.tw/upload/images/20220110/201074529N4JzBb1gu.png

本篇已同步發表至個人部落格
https://coolmandiary.blogspot.com/2022/01/net-core-web-api22swagger.html


上一篇
.Net Core Web Api_筆記21_Swagger及OpenAPI介紹與配置使用方式_API管理與測試探討
下一篇
.Net Core Web Api_筆記23_api結合EFCore資料庫操作part1_專案前置準備
系列文
.NET Core WebApi網頁應用開發25

尚未有邦友留言

立即登入留言