javascript - 如何将 json POST 数据作为对象传递给 Web API 方法?

标签 javascript asp.net-mvc json asp.net-mvc-4 asp.net-web-api

ASP.NET MVC4 Web API 应用程序定义了 post 方法来保存客户。 客户在 POST 请求正文中以 json 格式传递。 post 方法中的客户参数包含属性的空值。

如何解决这个问题,以便发布的数据将作为客户对象传递?

如果可能,应该使用 Content-Type: application/x-www-form-urlencoded,因为我不知道如何在发布表单的 javascript 方法中更改它。

Controller :

public class CustomersController : ApiController {

  public object Post([FromBody] Customer customer)
        {
            return Request.CreateResponse(HttpStatusCode.OK,
            new
            {
                customer = customer
            });
        }
    }
}

public class Customer
    {
        public string company_name { get; set; }
        public string contact_name { get; set; }
     }

请求:

POST http://localhost:52216/api/customers HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

{"contact_name":"sdfsd","company_name":"ssssd"}

最佳答案

编辑:2017 年 10 月 31 日

同样的代码/方法也适用于 Asp.Net Core 2.0。主要区别在于,在 asp.net core 中,web api Controller 和 Mvc Controller 都合并为单个 Controller 模型。因此,您的返回类型可能是 IActionResult 或其实现之一(例如:OkObjectResult)


使用

contentType:"application/json"

发送时需要使用JSON.stringify方法转成JSON字符串,

并且模型绑定(bind)器会将 json 数据绑定(bind)到您的类对象。

下面的代码可以正常工作(经过测试)

$(function () {
    var customer = {contact_name :"Scott",company_name:"HP"};
    $.ajax({
        type: "POST",
        data :JSON.stringify(customer),
        url: "api/Customer",
        contentType: "application/json"
    });
});

结果

enter image description here

contentType 属性告诉服务器我们正在以 JSON 格式发送数据。由于我们发送的是 JSON 数据结构,模型绑定(bind)会正常进行。

如果您检查 ajax 请求的 header ,您可以看到 Content-Type 值设置为 application/json

如果你没有明确指定 contentType,它将使用默认的内容类型 application/x-www-form-urlencoded;


于 2015 年 11 月编辑以解决评论中提出的其他可能问题

发布复杂对象

假设您有一个复杂的 View 模型类作为您的 web api 操作方法参数,如下所示

public class CreateUserViewModel
{
   public int Id {set;get;}
   public string Name {set;get;}  
   public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
  public int Id {set;get;}
  public string Code {set;get;}
}

你的 web api 端点就像

public class ProductController : Controller
{
    [HttpPost]
    public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
    {
        // I am just returning the posted model as it is. 
        // You may do other stuff and return different response.
        // Ex : missileService.LaunchMissile(m);
        return m;
    }
}

在撰写本文时,ASP.NET MVC 6 是最新的稳定版本,在 MVC6 中,Web api Controller 和 MVC Controller 都继承自 Microsoft.AspNet.Mvc.Controller 基类。

要从客户端向方法发送数据,下面的代码应该可以正常工作

//Build an object which matches the structure of our view model class
var model = {
    Name: "Shyju",
    Id: 123,
    Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: "../product/save",
    contentType: "application/json"
}).done(function(res) {       
    console.log('res', res);
    // Do something with the result :)
});

模型绑定(bind)适用于某些属性,但不是全部!为什么?

如果不使用[FromBody]属性修饰web api方法参数

[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
    return m;
}

并在不指定 contentType 属性值的情况下发送模型(原始 javascript 对象,不是 JSON 格式)

$.ajax({
    type: "POST",
    data: model,
    url: "../product/save"
}).done(function (res) {
     console.log('res', res);
});

模型绑定(bind)将适用于模型上的平面属性,而不是类型为复杂/其他类型的属性。在我们的例子中,IdName 属性将正确绑定(bind)到参数 m,但 Tags 属性将是一个空列表。

如果您使用的是短版本,也会出现同样的问题,$.post 在发送请求时将使用默认的 Content-Type。

$.post("../product/save", model, function (res) {
    //res contains the markup returned by the partial view
    console.log('res', res);
});

关于javascript - 如何将 json POST 数据作为对象传递给 Web API 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20226169/

相关文章:

javascript - jQuery 在两个项目之间切换并关闭另一个

javascript - 导航上没有背景颜色

javascript - Knockout映射插件[create,update]: objects created,无法更新

asp.net - 如何在 ASP.NET 和 Windows 服务中使用相同的 DI 代码

iOS:从 JSON 切换到 CoreData 以保留本地持久数据;这实用吗?数组内的字典 数组内的字典

php - 尝试动态填充选择列表时的 Json 结果 "undefined"

javascript - 使用本地存储在 2 个样式表之间切换(一次切换)

asp.net-mvc - ASP.NET MVC 本地化最佳实践?

asp.net-mvc - 如何设置路由以使某些 Controller 操作由 Angular 处理

javascript - 在 Google apps 脚本中获取 json 数组中的键->值