简体   繁体   English

枚举响应是数值而不是字符串

[英]Enum response is numeric value and not string

For all my other enum classes swagger shows the string definition but for one enum class that I use in my 'ExceptionMiddleware' class it shows the numeric value.对于我所有其他枚举类 swagger 显示字符串定义,但对于我在“ExceptionMiddleware”class 中使用的一个枚举 class,它显示数值。 But in the swagger documentation example it shows the string value..但在 swagger 文档示例中,它显示了字符串值..

My enum class:我的枚举 class:

public enum ErrorCode
{
    Undefined = -1,
    None = 0,

    ContractNotFound = 1000
}

One of my other enum classes that doesn't have this "problem":我的其他枚举类之一没有这个“问题”:

public enum ContractStatus
{
    Undefined = 0,
    Created = 1,
    Valid = 2,
    Invalid = 3
}

在此处输入图像描述

A result when the contract is not found:找不到合约时的结果:

在此处输入图像描述

I also have to add '[JsonPropertyName("errorCode")]' so the properties start with a lowercase letter.我还必须添加 '[JsonPropertyName("errorCode")]' 以便属性以小写字母开头。 For all my other models this is not needed...对于我所有的其他型号,这不是必需的......

The class: class:

public class ExceptionResponse
{
    [JsonPropertyName("errorCode")]  
    public ErrorCode ErrorCode { get; set; }

    [JsonPropertyName("errorCodeLabel")]
    public string ErrorCodeLabel { get; set; }

    [JsonPropertyName("errorMessage")]
    public string ErrorMessage { get; set; }
}

Configuration in 'Program.cs': “Program.cs”中的配置:

o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

If I remove this all enum's show numeric values instead of string values.如果我删除这个所有枚举的显示数值而不是字符串值。

How I build the 'ExceptionResponse' model in my 'ExceptionMiddleware' class:我如何在我的“ExceptionMiddleware”class 中构建“ExceptionResponse”model:

var exceptionResponse = new ExceptionResponse()
        {
            ErrorCode = ErrorCode.Undefined,
            ErrorCodeLabel = ErrorCode.Undefined.ToString(),
            ErrorMessage = "A random message."
        };

And if there is an error:如果有错误:

await httpContext.Response.WriteAsync(JsonSerializer.Serialize(exceptionResponse));

Because you are manually serializing, you are bypassing the registered middleware that contains your converter.因为您是手动序列化,所以您正在绕过包含您的转换器的已注册中间件。 You need to pass an options instance to your serialize call that includes the converter.您需要将选项实例传递给包含转换器的序列化调用。

var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter());

await httpContext.Response.WriteAsync(JsonSerializer.Serialize(exceptionResponse, options));

It is considered a best practice to cache your serializer options as a static field so that you are not re-creating them each call to Serialize, since this has severe performance repercussions in older versions of System.Text.Json .将序列化程序选项缓存为 static 字段被认为是最佳实践,这样您就不会在每次调用序列化时重新创建它们,因为这对旧版本的System.Text.Json有严重的性能影响。

public class ContainingClass
{
    private static readonly JsonSerializerOptions s_options = new()
    {
        Converters =
        {
            new JsonStringEnumConverter()
        }
    }
}

You can put this attribute above your Enum declaration.您可以将此属性放在 Enum 声明之上。 Something like this像这样的东西

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum ErrorCode
{
    Undefined = -1,
    None = 0,

    ContractNotFound = 1000
}

Note that this is for .net core 3 and above.请注意,这是针对 .net 核心 3 及更高版本。 More info for the built-in converter is here: https://learn.microsoft.com/en-us/do.net/api/system.text.json.serialization.jsonstringenumconverter?view.net-7.0内置转换器的更多信息在这里: https://learn.microsoft.com/en-us/do.net/api/system.text.json.serialization.jsonstringenumconverter?view.net-7.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM