如何从.Net Web API 2 Owin Auth禁用Camelcase属性转换

时间:2016-06-29 14:24:58

标签: c# asp.net angularjs asp.net-web-api owin

我实施了一个AngularJS项目。服务器端我使用.NET Web API(C#)编码。我通过安装NuGet包https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors在Web API中启用了 CORS 我正在使用 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"
            };
    }
}

模型类是

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

在AngularJS中,我收到的响应消息就像

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

我不需要这种Camelcase格式化,我需要我所提供的。

我期待的输出应该是

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

我在Owin Implementation之后遇到了这个问题。请帮助我...

1 个答案:

答案 0 :(得分:2)

WebApiConfig.cs

中添加以下格式化程序
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver()
};

这会将Camel-Case Formatting恢复为默认值。

ContractResolver = new DefaultContractResolver()