Using Microsoft.AspNetCOre.OData 7.0.1
, if I have a list of Models that are NOT in the database, the JSON result always comes back as PascalCase instead of camelCase. How can I get my list to be camelCase?
Relative example below:
My model that is NOT in the database.
public class Widget
{
public string Id { get; set; }
public string Name { get; set; }
}
My controller
[Route("api/[controller]")]
public class WidgetController : ODataController
{
[EnableQuery()]
public IActionResult GetWidgets()
{
// Create list of ten Widgets
var widgetsList = new List<Widget>();
for(var i = 0; i < 10; i++) {
widgetsList.Add(new Widget() { Id = i, Name = $"Widget {i}" });
}
return this.Ok(widgetsList);
}
}
/api/GetWidgets?$select=name returns in the following format
{ Name: "Widget" }
Even though Widget
is not in the database, you can add it to the Entity Data Model (EDM). The EDM probably has camel case as its convention. Widget
will pick up that convention.
var builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();
builder.EntitySet<Widget>("Widgets");
_edmModel = builder.GetEdmModel();
Here is a sample OData fork of the odata/webapi repository.
Set the MVC JSON options in ConfigureServices
. Now JSON responses will be in camel case.
services
.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With