I have this example as a response type when a record is not found :
public class NotFoundResponse
{
/// <example>RecordNotFound</example>
public ErroCodes ErrorCode { get; set; }
/// <example>5</example>
public int NumericErrorCode { get; set; }
/// <example>A random error message.</example>
public string ErrorMessage { get; set; }
}
My ErrorCodes enum class contains the follow fields :
public enum ErrorCodes
{
None = 0,
...
RecordNotFound = 5
}
But as you can see in the sample response it always takes the first field 'None'. How can I put there whatever error code I want?
In the sample response it always takes the first field 'None'. How can I put there whatever error code I want?
Based on your shared code snippet and description it appeared that you would like to set enum value other than the defult or any value you want to assign while displying swagger API document.
If you look into SwaggerGenOptionsExtensions.cs within swagger DependencyInjection extension class you would seen UseInlineDefinitionsForEnums property which would allow you to define your custom enum value which you want to display on your swagger API docs other than the default one. Have a look on following image:
Implementation:
You can define your expected enum value on your class annotations as following:
public class NotFoundResponse
{
[DefaultValue(ErrorCodes.MyCustomErrorCode)]
public ErrorCodes ErrorCode { get; set; }
public int NumericErrorCode { get; set; }
public string ErrorMessage { get; set; }
}
public enum ErrorCodes
{
None = 0,
RecordNotFound = 5,
FileNotFound = 7,
MyCustomErrorCode = 4004,
}
Program.cs file:
Within your program.cs file you have to explicitely define that enum value would be selected as per your custom defination.
builder.Services.AddSwaggerGen(modifyEnumDefultValue =>
{
modifyEnumDefultValue.UseInlineDefinitionsForEnums();
});
Output:
Note: You can get more details on swagger official document here.