https://github.com/RSuter/NJsonSchema/wiki/JsonSchemaGenerator#integer-vs-string-enumerations

Integer vs string enumerations

JSON Schema supports integer and string enumerations. In Json.NET, enums are serialized as integer by default. However you can mark a property with the JsonConverterAttribute so that it is serialized as string. NJsonSchema looks for these attributes and generates the enum JSON Schema respecting this attribute:

// Only this property is serialized as string
[JsonConverter(typeof(StringEnumConverter))]
public Gender Gender { get; set; } // Always serialized as string
[JsonConverter(typeof(StringEnumConverter))]
public enum Gender
{
...
}

Also see Enums

https://stackoverflow.com/questions/36452468/swagger-ui-web-api-documentation-present-enums-as-strings

So I think I have a similar problem. I'm looking for swagger to generate enums along with the int -> string mapping. The API must accept the int. The swagger-ui matters less, what I really want is code generation with a "real" enum on the other side (android apps using retrofit in this case).

So from my research this ultimately seems to be a limit of the OpenAPI specification which Swagger uses. It's not possible to specify names and numbers for enums.

The best issue I've found to follow is https://github.com/OAI/OpenAPI-Specification/issues/681 which looks like a "maybe soon" but then Swagger would have to be updated, and in my case Swashbuckle as well.

For now my workaround has been to implement a document filter that looks for enums and populates the relevant description with the contents of the enum.

 GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.DocumentFilter<SwaggerAddEnumDescriptions>(); //disable this
//c.DescribeAllEnumsAsStrings()

SwaggerAddEnumDescriptions.cs:

using System;
using System.Web.Http.Description;
using Swashbuckle.Swagger;
using System.Collections.Generic; public class SwaggerAddEnumDescriptions : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
// add enum descriptions to result models
foreach (KeyValuePair<string, Schema> schemaDictionaryItem in swaggerDoc.definitions)
{
Schema schema = schemaDictionaryItem.Value;
foreach (KeyValuePair<string, Schema> propertyDictionaryItem in schema.properties)
{
Schema property = propertyDictionaryItem.Value;
IList<object> propertyEnums = property.@enum;
if (propertyEnums != null && propertyEnums.Count > )
{
property.description += DescribeEnum(propertyEnums);
}
}
} // add enum descriptions to input parameters
if (swaggerDoc.paths.Count > )
{
foreach (PathItem pathItem in swaggerDoc.paths.Values)
{
DescribeEnumParameters(pathItem.parameters); // head, patch, options, delete left out
List<Operation> possibleParameterisedOperations = new List<Operation> { pathItem.get, pathItem.post, pathItem.put };
possibleParameterisedOperations.FindAll(x => x != null).ForEach(x => DescribeEnumParameters(x.parameters));
}
}
} private void DescribeEnumParameters(IList<Parameter> parameters)
{
if (parameters != null)
{
foreach (Parameter param in parameters)
{
IList<object> paramEnums = param.@enum;
if (paramEnums != null && paramEnums.Count > )
{
param.description += DescribeEnum(paramEnums);
}
}
}
} private string DescribeEnum(IList<object> enums)
{
List<string> enumDescriptions = new List<string>();
foreach (object enumOption in enums)
{
enumDescriptions.Add(string.Format("{0} = {1}", (int)enumOption, Enum.GetName(enumOption.GetType(), enumOption)));
}
return string.Join(", ", enumDescriptions.ToArray());
} }

This results in something like the following on your swagger-ui so at least you can "see what you're doing":

NSwag enum的更多相关文章

  1. NSwag生成客户端调用代码

    NetCore2.1 WebAPI 根据swagger.json自动生成客户端代码 https://www.cnblogs.com/hunanzp/p/9297361.html 前言 上一篇博客中我们 ...

  2. .net core的Swagger接口文档使用教程(二):NSwag

    上一篇介绍了Swashbuckle ,地址:.net core的Swagger接口文档使用教程(一):Swashbuckle 讲的东西还挺多,怎奈微软还推荐了一个NSwag,那就继续写吧! 但是和Sw ...

  3. Swift enum(枚举)使用范例

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  4. 枚举:enum

    枚举 所谓枚举就是指定好取值范围,所有内容只能从指定范围取得. 例如,想定义一个color类,他只能有RED,GREEN,BLUE三种植. 使用简单类完成颜色固定取值问题. 1,就是说,一个类只能完成 ...

  5. Asp.Net 将枚举类型(enum)绑定到ListControl(DropDownList)控件

    在开发过程中一些状态的表示使用到枚举类型,那么如何将枚举类型直接绑定到ListControl(DropDownList)是本次的主题,废话不多说了,直接代码: 首先看工具类代码: /// <su ...

  6. 用枚举enum替代int常量

    枚举的好处: 1. 类型安全性 2.使用方便性 public class EnumDemo { enum Color{ RED(3),BLUE(5),BLACK(8),YELLOW(13),GREEN ...

  7. The Java Enum: A Singleton Pattern [reproduced]

    The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...

  8. c# (ENUM)枚举组合类型的谷歌序列化Protobuf

    c# (ENUM)枚举组合类型的谷歌序列化Protobuf,必须在序列化/反序列化时加上下面: RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru ...

  9. (转)C# Enum,Int,String的互相转换 枚举转换

    Enum为枚举提供基类,其基础类型可以是除 Char 外的任何整型.如果没有显式声明基础类型,则使用 Int32.编程语言通常提供语法来声明由一组已命名的常数和它们的值组成的枚举. 注意:枚举类型的基 ...

随机推荐

  1. 前端 HTML 注释

    单行注释 <!--注释内容--> <!DOCTYPE html> <!-- 页面根节点开始--> <html lang="en"> ...

  2. js-jquery-SweetAlert【二】配置方法

    一.配置 Argument Default value 含义   Description title null (required) 模态对话框的标题.它可以在参数对象的title参数中设置,也可以在 ...

  3. [wx]自然数学规律

    有趣的数学规律 椭圆 双曲线 抛物线都叫圆锥曲线 它们跟圆锥有着怎样的关系? 他们都是圆锥与平面在不同姿势下交配的产物. 参考 椭圆 抛物线 小结 e: 离线率 P: 任意一点 F: 焦点 准线: 一 ...

  4. PAT 1070 Mooncake[一般]

    1070 Mooncake (25)(25 分) Mooncake is a Chinese bakery product traditionally eaten during the Mid-Aut ...

  5. 机器学习理论基础学习14.1---线性动态系统-卡曼滤波 Kalman filter

    一.背景 动态模型 = 图 + 时间 动态模型有三种:HMM.线性动态系统(kalman filter).particle filter 线性动态系统与HMM的区别是假设相邻隐变量之间满足线性高斯分布 ...

  6. 训练/验证/测试集设置;偏差/方差;high bias/variance;正则化;为什么正则化可以减小过拟合

    1. 训练.验证.测试集 对于一个需要解决的问题的样本数据,在建立模型的过程中,我们会将问题的data划分为以下几个部分: 训练集(train set):用训练集对算法或模型进行训练过程: 验证集(d ...

  7. 20165324 《网络对抗技术》week1 Kali的安装与配置

    20165324 <网络对抗技术>week1 Kali的安装与配置 安装过程 VMware安装过程省略 kali 光盘映像文件的下载 新建虚拟机,并导入. 安装Tools 在菜单中,选择虚 ...

  8. 数据结构线性表的动态分配顺序存储结构算法c语言具体实现和算法时间复杂度分析

    #include<stdio.h>#include<stdlib.h>//线性表的动态分配顺序存储结构#define LIST_INIT_SIZE 100//线性表存储空间的初 ...

  9. Django初级手册3-视图层与URL配置

    设计哲学 在Django中一个视图有指定函数和指定模版组成.对于某些特定的应用应该分成若干视图.例如博客系统 Blog主页面 详细页面入口 基于年的页面展示 基于月的页面展示 基于天的页面展示 评论行 ...

  10. python3 列表的常用方法

    Python3中常用的列表方法(method) 见:help(list) 方法 意义 L.index(v [, begin[, end]]) 返回对应元素的索引下标, begin为开始索引,end为结 ...