Ash
Ash

Reputation: 6035

ASP .Net core web api serialization issue for property names with underscore

The simplest version of the problem is shown by creating a new ASP .NET core web api project. Adding this class

public class TestClass
{
    public string AAAA_BBBB { get; set; } = "1";
}

And this controller method

[HttpGet("GetTestClass")]
public TestClass GetTestClass()
{
   return new TestClass();
}

results in this response

{
   "aaaA_BBBB": "1"
}

After experimenting, it looks like anything which has an underscore in it is treated this way. All the characters in the bit before the FIRST underscore except for the last character in that set get converted into lower case.

So

Why is this happening and how do I fix it?

Upvotes: 0

Views: 1248

Answers (1)

Chen
Chen

Reputation: 5164

By default Web API serializes the fields of types that have a [Serializable] attribute (e.g. Version).That's what the Web API guys wanted.

You can decorate with a property name like so:

[JsonPropertyName("AAAA_BBBB")]
public string AAAA_BBBB { get; set; } = "1";

Or,you can refer to these two links:Link1 and Link2 to stop Web API doing it in JSON.

Update

The same effect can be achieved using the following code in Startup

services.AddControllersWithViews().
                AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                    options.JsonSerializerOptions.PropertyNamingPolicy = null;
                });

Upvotes: 2

Related Questions