The Web API serializes all the public properties into JSON. In the older versions of Web API, the default serialization property was in PascalCase. When we are working with .NET based applications, the casing doesn’t matter. But when the API is consumed by another application, such as Angular JS or any other application, then most of the cases are CamelCase as per the JavaScript standard. Moreover, most of the developers are familiar with this type of naming.
ASP.NET Core becomes the camelCase serialization as default. If we have migrated the application from Web API 2.0 to .NET core, the application may not be working. However, we can configure the serialization to PascalCase.
Product.cs
- public class Product
- {
- public int Id { get; set; }
-
- public string Name { get; set; }
-
- public string Description { get; set; }
-
- }
ProductController.cs- [Route("api/[controller]")]
- public class ProductController : Controller
- {
- [HttpGet("{id}")]
- public Product Get(int id)
- {
- return new Product()
- {
- Id=id,
- Name="test",
- Description="Description"
- };
- }
-
- }
Startup.cs- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
-
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- app.UseMvc();
-
- }
- }
While executing the API service, the result will be as follows.
- {"id":1,"name":"test","description":"Description"}
To configure the Service to PascalCase, we need to change the ContractResolver for the JSON Serializer (DefaultContractResolver).
Startup.cs
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc()
- .AddJsonOptions(o => o.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- app.UseMvc();
-
- }
- }
- {"Id":1,"Name":"test","Description":"Description"}