Odata controllers in my project returns jsons with casing as it is in class so PascalCase.
I want to make them return json with camelCase props.
Controllers which don’t use OData returns camelCase jsons by default.
To configure Odata I’m using IMvcBuilder.AddOData()
method (extension method from Microsoft.AspNetCore.OData
). All my OData controllers inherits from Microsoft.AspNetCore.OData.Rounting.Controllers.ODataController
and methods have [EnableQuery]
attribute
I guess I should chain AddJsonOptions
method after that, but don’t know what to pass there. Internet says it should be opt => opt.SerializerSettings.ContractResolver = new DefaultContractResolver()
, but opt here is JsonOptions and doesn’t have SerializerSettings
property.
Edit: Chaining .AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
after AddOData
doesn’t help.
Edit2: Adding [JsonProperty]
attributes on model properties also doesn’t help.
Edit3: I try to add custom ODataSerializerProvider
by register it in 3rd argument of AddRouteComponents
, but constructor isn’t hit neither at app start nor endpoint call.
2
Answers
The problem was that I was using
AddRouteComponents
method and custom Edm model. Without itAddJsonObject
chained method works. Described here: https://github.com/OData/AspNetCoreOData/blob/main/docs/camel_case_scenarios.mdShort answer: Call builder.EnableLowerCamelCase()
Another way answered before is remove AddRouteComponents() call. But this will make Odata only return array data only. For example:
To return only array data, and remove another properties: