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. But in the swagger documentation example it shows the string value..
My enum 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. For all my other models this is not needed...
The 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' :
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 :
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));
CodePudding user response:
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
.
CodePudding user response:
You can put this attribute above your Enum declaration. 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. More info for the built-in converter is here: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonstringenumconverter?view=net-7.0