Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I configure asp.net so some responses are serialized as camelCase and some as PascalCase?

I have an API with two clients: OldClient and newClient. I currently have this in Startup.cs so my json responses are serialized as PascalCase, i.e. as per all my .net objects which have first letter capitalized.

    services.AddControllers().AddJsonOptions(jsonOptions =>
    {
        // So json output is like 'SomeId' instead of 'someId':
        jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
        ...
    }

OldClient loves this format. However, newClient would really prefer camelCase.

Is there a way I can configure my app to respond with camelCase for newClient requests and PascalCase for OldClient requests? newClient can send a header to indicate that it wants camelCase.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can check out this issue on aspnetcore’s github page

The possibility of using specific JSON Serializer Options on a per-controller basis hasn’t been implemented yet. It has been moved to ".net 8 planning", which means it’s still a ways-away.

Meanwhile, you could work around this issue by:

  1. For data reception and model-binding, you could create a Custom ModelBinder by implementing IModelBinder interface in a ModelBinderAttribute in order to utilize your specific JSON Serialization options. Then, you could simply add the attribute to the endpoints where you need it.

  2. For data responses, you could simply use:

    return new JsonResult([object], [CustomJSONSerializationSettings]);

It’s quite annoying to have to modify these per-endpoint, but it seems like it’s the only way until the feature is added in .net 8 (if we’re lucky).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading