0

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

  • AAAA_BBBB becomes aaaA_BBBB
  • AAAAAAAA_BBB_CCC_DDD becomes aaaaaaaA_BBB_CCC_DDD
  • A_BBB becomes a_BBBB
  • AA_BB becomes aA_BB

Why is this happening and how do I fix it?

2
  • What json serializer are you using? Commented Jul 7, 2022 at 11:50
  • The default one used by WebAPI. Not doing anything special for it Commented Jul 8, 2022 at 1:22

1 Answer 1

2

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;
                });
Sign up to request clarification or add additional context in comments.

2 Comments

This solution works but I can't use it due to certain constraints. I'm using .net 5.0 frmaework. The code in the links you posted build if I add a reference to Microsoft.AspNet.WebAPI/5.2.9 but it looks like this is meant for projects target .netFramework4.8 because I keep getting an error I cant get around -> Could not load type "System.Web.Routing.RouteTable" This is the bit of code I'm trying to get working var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.UseDataContractJsonSerializer = true;
I updated my answer, you can test it.@Ash

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.