zoukankan      html  css  js  c++  java
  • ASP.NET Core – Swagger

    前言

    Swagger (OpenAPI) 是一套 Web API 文档规范. 

    ASP.NET Core 有 2 个 Library 可以帮我们从 Web API Controller convert to 文档哦

    一个是 Swashbuckle

    另一个是 NSwag

    NSwag 还能直接生产 client code 比如 typescript 等等哦. 但我是没有这个需求啦, 所以我用 Swashbuckle

    主要参考

    Get started with Swashbuckle and ASP.NET Core

    Controller action return types in ASP.NET Core web API

    安装 nuget

    dotnet add package Swashbuckle.AspNetCore

     ASP.NET Core 6.0 模板已经有自带的了.

    跑起来长这样

    配置 docs

    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1.0", new OpenApiInfo
        {
            Title = "Project Web API",
            Version = "v1.0",
            Description = "Project Web API version 1.0",
            Contact = new OpenApiContact
            {
                Name = "Derrick Yam",
                Email = "hengkeat87@gmail.com",
            },
        });
    });

    UI Endpoint

    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1.0/swagger.json", "Project Web API v1.0");
        options.DocExpansion(DocExpansion.None);
    });

    开启 XML comments

    打开 project.csproj, 添加 2 行, Nowarn 是去掉警告, 不然很烦.

    <PropertyGroup>
      <GenerateDocumentationFile>true</GenerateDocumentationFile>
      <NoWarn>$(NoWarn);1591</NoWarn>
    </PropertyGroup>

    添加

    services.AddSwaggerGen(options =>
    {
        ... 
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        options.IncludeXmlComments(xmlPath);
    });

    Controller > Action

    action 大概长这样

    /// <summary>
    /// some summary here...
    /// </summary>
    /// <remarks>
    /// some remark here...
    /// </remarks>
    /// <param name="dto">Customer information</param>
    /// <returns>A newly created customer</returns>
    /// <response code="201">Returns the newly created customer</response>
    /// <response code="400">When DTO invalid</response>   
    [HttpPost("customers")]
    [Consumes(MediaTypeNames.Application.Json)] // 接收 json
    [Produces(MediaTypeNames.Application.Json)] // 返回 json
    [ProducesResponseType(StatusCodes.Status201Created, Type = typeof(Customer))] // 有可能返回 200, 可以定义类型, 或者用 ActionResult 定义(那这里就不需要了)
    [ProducesResponseType(StatusCodes.Status400BadRequest)] // 有可能返回 400
    public async Task<ActionResult<Customer>> CreateCustomerAsync(
        [FromBody] CreateCustomerDTO dto
    )
    {
        ...
        return CreatedAtAction("GetById", new { customerId = customer.CustomerId }, customer);
    }

    关于 return type 可以看这篇, 这些注释最终就会出现在 docs里.

    ODataController action 长这样 (just example 不要管 versioning 那些)

    [ApiController]
    [ApiVersion("1.0")]
    public class CustomersController : ODataController
    {
        private readonly ApplicationDbContext _db;
    
        public CustomersController(
            ApplicationDbContext db
        )
        {
            _db = db;
        }
    
        [HttpGet("customers")]
        [Produces(MediaTypeNames.Application.Json)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [EnableQuery]
        public ActionResult<IEnumerable<Customer>> GetCustomers()
        {
            return Ok(_db.Customers);
        }
    
        [HttpGet("customers/{id}")]
        [Produces(MediaTypeNames.Application.Json)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [EnableQuery]
        public ActionResult<Customer> GetByIdAsync(int id)
        {
            return Ok(SingleResult.Create(_db.Customers.Where(c => c.CustomerId == id)));
        }
    }
    View Code
  • 相关阅读:
    杨晓峰-Java核心技术-6 动态代理 反射 MD
    ARouter 路由 组件 跳转 MD
    领扣-5 最长回文子串 Longest Palindromic Substring MD
    算法 递归 迭代 动态规划 斐波那契数列 MD
    二叉树 遍历 先序 中序 后序 深度 广度 MD
    算法 数组中出现次数最多的数字 MD
    领扣-754 到达终点数字 Reach a Number MD
    领扣-1/167 两数之和 Two Sum MD
    文件 File 常见操作 工具 MD
    IO流 简介 总结 API 案例 MD
  • 原文地址:https://www.cnblogs.com/keatkeat/p/15458744.html
Copyright © 2011-2022 走看看