【问题标题】:Passing data from an jQuery Ajax call to an MVC ApiController Action is losing data将 jQuery Ajax 调用中的数据传递给 MVC ApiController Action 正在丢失数据
【发布时间】:2017-02-01 22:03:24
【问题描述】:

首先,我只想说这里已经发布了很多类似的问题,但我已经尝试了所有的解决方案,但没有任何乐趣。

我有一个 MVC ApiController Action,其签名是:

    public void Post([FromBody] Employee employee)

我尝试过使用或不使用 [FromBody]。

我的 Employee 类有 5 个基本类型的成员,int、string、string、string、double

我正在使用 jQuery Ajax 从单独的域(都在我的本地主机上使用 Cors)调用 Action,如下所示:

    $.ajax({
        url: "http://localhost:55555/api/Employees",
        type: "POST",
        headers: {
            "Authorization": "Bearer " + sessionStorage.getItem("accessToken")
        },
        data: {
            Id: 100,
            FirstName: "Fred",
            LastName: "Blogs",
            Gender: "Male",
            Salary: 100000
        },
        // ...

这绝对没问题。授权没有问题。 Controller 上的 Employee 对象填充了这些数据。但我想做的是以更“结构化”的方式发送数据。所以我的数据看起来像这样:

        data: {
            employee: employee
        },

我已经尝试了所有我能想到的格式化员工的方法。指定所有组合:

        contentType: "application/json; charset=utf-8",
        dataType: "json", 

结合不同的方式来“字符串化”我的员工对象:

    var employee = {
        Id: 100,
        FirstName: "Fred",
        LastName: "Blogs",
        Gender: "Male",
        Salary: 100000
    };

    employee = JSON.stringify({ "employee": employee });
    employee = JSON.stringify(employee);

如果这是相关的(作为一个更简单的例子),我的 ApiController 上也有这个方法:

public void Delete([FromBody] int employeeId)

同样,我无法以“所需”方式传递employeeId。

我什至无法得到:

        data: {
            employeeId: 100
        },

上班!?!

如果我将其更改为 [FromUri] 并在调用 Url 中指定“?employeeId=100”,我可以让 Delete 方法工作。

我希望我可以在不同的调用中更加一致,并始终以 JSON 格式传递一个“对象”。

有人有什么想法可以帮助我进步吗?

谢谢。

有关 Delete 调用的更多信息。

如果我使用 Postman,请删除身份验证要求,指定 Content-Type "application/json" 在 header 和 body 中的 employeeId = 100 中,Postman 返回:

{
  "Message": "The request is invalid.",
  "MessageDetail": "The parameters dictionary contains a null entry for parameter 'employeeId' of non-nullable type 'System.Int32' for method 'Void Delete(Int32)' in 'WebApi.Controllers.EmployeesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}

【问题讨论】:

    标签: javascript jquery ajax asp.net-apicontroller


    【解决方案1】:

    我认为“DELETE”不会像“POST”一样传递正文,因此如果您使用以下类型调用 ajax 调用,[FromBody] 将不起作用:“Delete”。

    至于员工电话后,我也看到过类似的问题。我能找到的唯一解决方法是创建一个包装员工的包装类。

    public class EmployeeWrapper {
        public Employee employee {get; set;}
    }
    

    那么你让 EmployeeWrapper 成为 Post 方法的参数。

     public void Post([FromBody] EmployeeWrapper employeeWrapper)  {
          Employee employee = employeeWrapper.employee;
          ...
    

    这让您可以使用 ajax 数据调用:

    data: {
            employee: employee
        },
    

    【讨论】:

    • 这行得通。正如您似乎指出的那样,这有点混乱。我认为客户端的 stringify() 选项之一会以我可以直接使用 Employee 对象的方式格式化数据。
    • 关于 Delete() 的公平评论。我稍后会调查。我认为 Post/Put 应该是一样的。
    【解决方案2】:

    将data 更改为:

    data: JSON.stringify({ employee : employee })
    

    【讨论】:

    • 我试过这个。再次使用 dataType / contentType 的所有组合。该方法被调用,但 Employee 对象的所有属性在 ApiController Action 中仍然具有它们的默认 null 值,即 0 值。
    • 尝试将contentType: 'application/json', dataType: "json" 添加到您的$.ajax 设置中
    • 服务器上的员工对象仍然有默认值: var employee = { Id: 100, FirstName: "Fred", LastName: "Blogs" Gender: "Male", Salary: 100000 }; $.ajax({ url: "http://..., type: "POST", headers: { "Authorization": "Bearer" + sessionStorage.getItem("accessToken") }, contentType: "application/json" ,数据类型:“json”,数据:JSON.stringify({员工:员工}),
    【解决方案3】:

    以下组合终于解决了我的问题。

        var employee = {
            Id: 100,
            FirstName: "Fred",
            LastName: "Blogs",
            Gender: "Male",
            Salary: 100000
        };
    
        employee = JSON.stringify(employee);
    
        //...
        contentType: "application/json",
        data: employee,
        //...
    

    我没有早点到达的原因之一是我倾向于用花括号包围数据:{ ... }。这导致它失败。

    还设法让 DELETE 以完全相同的方式在消息正文中工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-12
      • 2020-11-22
      • 2020-02-15
      • 2021-04-14
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      相关资源
      最近更新 更多