Web API 2.0使用pascal-case模型以camel-case形式接收JSON数据

Web API 2.0 recieve JSON data in camel-case with a pascal-case Model

本文关键字:数据 JSON camel-case API 使用 模型 pascal-case Web      更新时间:2023-09-26

我正在尝试对Web API进行PUT调用。我已经在WebApiConfig.cs中设置了以下内容,以处理将数据发送回camel情况下的Web项目。

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver
    = new CamelCasePropertyNamesContractResolver();

我的数据来自剑道UI网格中的一行。进行Ajax调用的javascript如下:

...    
    save: function(e) {
        var dataItem = e.model;
        $.ajax({
            url: apiUrl() + "/roleLocationSecurable",
            type: 'PUT',
            headers: {
                'Authorization': 'Bearer ' + getTwtToken(),
                'LocationId': getCurrentLocation()
            },
            data: JSON.stringify(dataItem),
            dataType: 'json'
        }).done(function(data){
            //stuff when finished
        });
    }
...

发送到Web API的数据如下所示:

"id":1,
"roleLocationId":5
"moduleId":5
...

Web API 2.0控制器上的操作如下:

[HttpPut]
[Route("roleLocationSecurable")
public IHttpActionResult UpdateRoleLocationSecurable(RoleLocationSecurableResource model)
{
    var roleLocationSecurable = Mapper.Map<RoleLocationSecurableResource, RoleLocationSecurable>(model);
    if(_roleService.UpdateRoleLocationSecurable(roleLocationSecurable))
    {
        return Ok();
    }
    return NotFound();
}

我的控制器期望的模型有这样的属性:

public int? Id {get;set;}
public int RoleLocationId {get;set;}
public int ModuleId {get;set;}
....

发生的情况是,我的Ajax调用正在启动,PUT调用的主体包括上面的所有信息,以及camel-case键。正在调用Web API控制器,但模型中的值没有填充任何内容(模型基本上是空白的(。

我认为我遇到的问题(也许我错了(是Web API控制器上的Action需要Pascal Case属性,而我的Ajax调用正在发送Camel Case。

既然CameraCasePropertyNamesContractResolver正在处理将数据序列化为camel-case,为什么它不处理反序列化?有没有一种简单易行的方法来解决这个问题?

如果您能对上述代码不起作用的原因提供任何帮助,我们将不胜感激。

services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver
            = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    });

如果您在,请将其添加到Startup.cs中。Net Core项目,它将与保持相同。Net类库。

您的ajax调用中似乎缺少contentType:"application/json"。为了让Web API正确处理内容协商和模型绑定,它必须知道传递的内容类型。如果不告诉Web API内容类型,它就无法将内容映射到模型,从而在Action中将其显示为null。以下是您更新的片段:

$.ajax({
    url: getApiUrl() + "/roleLocationSecurable",
    type: 'PUT',
    headers: {
        'Authorization': 'Bearer ' + getJwtToken(),
        'LocationId': getCurrentLocation()
    },
    data: dataItem,
    dataType: "json",
   **contentType: "application/json"**
})...

我能够测试这个,我看到了一个填充的模型。

您是否尝试过用JsonProperty注释模型属性。例如:

[JsonProperty("Id")]
public int? Id {get;set;}
[JsonProperty("RoleLocationId ")]
public int RoleLocationId {get;set;}
[JsonProperty("ModuleId ")]
public int ModuleId {get;set;}

请记住调用此程序集:using Newtonsoft.Json;