IR Punch IR Punch - 5 months ago 26
AngularJS Question

How to Disable Camelcase Property convertion from .Net Web API 2 Owin Auth

I Implemented an AngularJS Project. The Server Side I coded using .NET Web API (C#). I Enabled the CORS in the Web API by installing the NuGet Package https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors
I'm doing Authentication using Owin Auth https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Owin

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class SampleController : ApiController
{
[Authorize]
[HttpGet]
public string GetAuthorizeEmployee()
{
return new Employee()
{
EID = "EMP_1001",
User = "Ram@gmail.com",
Name = "Ram Kumar",
Mobile_Number = "9999911111"
};
}
}


The Model Classes are

public class Employee
{
public string EID { get; set; }
public string User { get; set; }
public string Name { get; set; }
public string Mobile_Number { get; set; }
}


In AngularJS, I'm getting the response message as like

{
"eID": "EMP_1001",
"user": "EMP_1001",
"name": "EMP_1001",
"mobile_Number": "EMP_1001"
}


I don't need this Camelcase Formatting, I need what I have given.

My expecting Output should be

{
"EID": "EMP_1001",
"User": "EMP_1001",
"Name": "EMP_1001",
"Mobile_Number": "EMP_1001"
}


I'm getting this issue after Owin Implementation. Kindly assist me...

Answer

Add the following Formatter in your WebApiConfig.cs

config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver()
};

This will revert the Camel-Case Formatting to default.

ContractResolver = new DefaultContractResolver()