Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Swagger下拉列表和json上显示枚举成员友好名称_C#_Asp.net Core_Enums_Model Binding - Fatal编程技术网

C# 在Swagger下拉列表和json上显示枚举成员友好名称

C# 在Swagger下拉列表和json上显示枚举成员友好名称,c#,asp.net-core,enums,model-binding,C#,Asp.net Core,Enums,Model Binding,我试图让枚举在swagger和响应中显示来自描述(或任何其他属性)的友好名称。还尝试在控制器操作中解析body/querystring上设置的友好名称,而不尝试请求或任何类型的验证错误。我还注意到,我使用的定制通用JsonConverter也不能正常工作。根本没有调用ReadJson()方法。我怎样才能让它工作 [JsonConverter(typeof(JsonEnumConverter<SortDirectionType>))] public enum SortDirection

我试图让枚举在swagger和响应中显示来自描述(或任何其他属性)的友好名称。还尝试在控制器操作中解析body/querystring上设置的友好名称,而不尝试请求或任何类型的验证错误。我还注意到,我使用的定制通用JsonConverter也不能正常工作。根本没有调用
ReadJson()
方法。我怎样才能让它工作

[JsonConverter(typeof(JsonEnumConverter<SortDirectionType>))]
public enum SortDirectionType
{
    [Description("asc")]
    ASCENDING,
    [Description("desc")]
    DESCENDING
}

这就是它为我所做的:

  services.AddSwaggerGen(c => {
  c.DescribeAllEnumsAsStrings();
});

我在这里想出了一个窍门。这可能不一定是你的解决方案,但如果你能让它工作,那么我很高兴我可以帮助你

最后将枚举格式更改为字符串而不是默认下拉列表。通过这种方式,我可以将asc/desc值发送到api。Swagger接受了这些值,并且没有抛出验证错误。我在.net核心api上编写的转换器也能够很好地转换它们

c.MapType<SortDirectionType>(() => new Schema { Type = "string", Format = "string" });
c.MapType(()=>newschema{Type=“string”,Format=“string”});
除此之外,您可能还希望禁用自动启动的asp.net core 2.2验证的默认行为。不确定他们为什么选择将其设置为默认行为

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});
services.Configure(选项=>
{
options.SuppressModelStateInvalidFilter=true;
});

感谢您的回复。不幸的是,这不是我想要的。我想使用Description属性中的字符串值,而不是枚举项本身的文本。这种方法也适用于其他自定义类型吗?除此之外,我相信是的。你能详细说明你所说的自定义类型是什么意思吗?它所做的一切都是告诉swagger在uicustom类型上将底层类型视为字符串,如在公共类Foo{public int A{get;set;}public int B{get;set;}}。我尝试使用
MapType
,但在文档中似乎没有显示为字符串。我最终使用了中建议的类型转换器
services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});