I am using a Minimal API to recreate an old REST service and so I need to mimic the functionality of the previous service as close as possible. Information in the old service is returned Pascal case and I know that there are some old clients that are case-sensitive. Out of the box .NET 6 serializes to camel case on the web but that can be overridden with code such as:
builder.Services.Configure<JsonOptions>(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
If a breakpoint is set I can see that the policy is originally set to camel case and then reset to null. If I then use JsonSerializer.Serialize
it works as expected. The only issue is if I use Results.OK(colection)
it is back to camel case as if it is ignoring the options settings. I can set all the property names with declarative attributes on the model class and that works as expected so inline declarations work but setting on the service level does not. So, what options is the 'Results.OK' response pipeline looking at?
EDIT: Corrected method name
There are actually two different JsonOptions
in Asp.Net core:
I think you're using the Mvc version - switching to the first one above should fix the issue and return the correct Json casing. The Results
class is a member of the Microsoft.AspNetCore.Http
namespace which could explain why it uses different JsonOptions
from Mvc.
You could create an alias at the top of the file (or just reference the full namespace):
using JsonOptions = Microsoft.AspNetCore.Http.Json.JsonOptions;
...
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.PropertyNamingPolicy = null;
});
Note that the options property name is different (JsonSerializerOptions
vs SerializerOptions
) but all the options should be the same.