When sending my properties in an HttpGet call all of them are coming in lowercase once they hit angular. How can I prevent this from happening
[HttpGet]
public List<MyModel> GetModel()
{
var model = _repo.GetModel();
return model;
}
public Class MyModel
{
public int Id {get; set; }
public string Name {get; set;}
}
these are coming into angular like this
return this.httpClient.get<any>( this.myEndPoint + '/GetMyModel');
{ id: 1, name: "John" }
I need them to stay the exact same case they are sent in
{ Id: 1, Name: "John" }
What you're asking is more specific to your API that's returning the data, not angular or JavaScript. Since you're working with C#, you have a couple of options:
1.) JsonProperty attribute. You could decorate your model with JsonProperty("Id"). Full disclosure, I have not tested this part, but it should work. There's a chance the JsonSerializationSettings might overwrite this. If so, see #2.
2.) Define custom JsonSerializationSettings to use Pascal Case instead of the default CamlCase
It's kind of strange the only option offered by default is CamelCase, so you have to create your own Json Naming Policy.
Example if you wanted camel case
services.AddMvc().AddJsonOptions( options => options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase )
So, you have to do this on your own (Example of Upper Case):
public class UpperCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name) =>
name.ToUpper();
}
Usage:
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = new UpperCaseNamingPolicy(),
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, options);
See this for more explanation: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?view=netcore-3.1#customize-json-names-and-values
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