I have a c# .net 8 minimal api witch takes as a parameter an enum:
app.MapGet("/{id}/attachments/{category}/{attachmentId}", async (
Guid id,
AttachmentCategory category,
string attachmentId) => {
...
})
Enum:
public enum AttachmentCategory
{
Documents,
Photos
}
I am using System.Text.Json
Serialization:
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
works:
https://localhost:1234/api/v1/item/b9c10df0-c974-4876-a3fa-d4b5e8140929/attachments/Documents/3abd9b3b-97e9-4668-b4b3-50cbcdac0220.pdf
does not work:
https://localhost:1234/api/v1/item/b9c10df0-c974-4876-a3fa-d4b5e8140929/attachments/documents/3abd9b3b-97e9-4668-b4b3-50cbcdac0220.pdf
Can I make lower case work? mybe both?
Problem 2: The enum parameter shows up in swagger as a string not as an enum
Is a IDocumentFilter
the only way to fix that?
To fix problem2,you may try:
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});
.....
app.MapGet("/{id}/attachments/{category}/{attachmentId}", (
Guid id,
[FromRoute] AttachmentCategory category,
string attachmentId) =>
{
.....
})
.WithOpenApi();
To fix problem 1:
app.MapGet("/{id}/attachments/{category}/{attachmentId}", (Guid id, [FromRoute]Category category, string attachmentId) =>
{
return attachmentId;
})
.WithOpenApi();
public class Category
{
[FromRoute]
public AttachmentCategory category { get; set; }
public static bool TryParse(string? value, IFormatProvider? provider,
out Category? categoryval)
{
var success= Enum.TryParse<AttachmentCategory>(value,
ignoreCase: true, out var categoryenumval);
if(success)
{
categoryval = new Category() { category = categoryenumval };
return true;
}
else
{
categoryval = null;
return false;
}
}
}
accroding to this document,related issue on github
but in this senaro,you need a filter to relapce category schema(if you need ,i will deliever it to you tomorrow)