skip to Main Content

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


  1. Chosen as BEST ANSWER

    The problem was that I was using AddRouteComponents method and custom Edm model. Without it AddJsonObject chained method works. Described here: https://github.com/OData/AspNetCoreOData/blob/main/docs/camel_case_scenarios.md


  2. Short answer: Call builder.EnableLowerCamelCase()

    private static IEdmModel GetEdmModel()
            {
                var builder = new ODataConventionModelBuilder();
                builder.EntitySet<User>("User");
    
                // => Add EnableLowerCamelCase here to resolve problem
                builder.EnableLowerCamelCase();
                return builder.GetEdmModel();
            }
    

    Another way answered before is remove AddRouteComponents() call. But this will make Odata only return array data only. For example:

    {
        "@odata.context": "https://localhost:5001/odata/$metadata#questions",
        "@odata.count": 30,
        "value": [
            {
                "name": "name 1"
            },
            {
                "name": "name 2"
            },
            ....
        ]
    }
    

    To return only array data, and remove another properties:

    [
            {
                "name": "name 1"
            },
            {
                "name": "name 2"
            },
            ....
        ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search