当前位置: 首页 > 知识库问答 >
问题:

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

澹台衡
2023-03-14

控制器:

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"}

共有1个答案

杜诚
2023-03-14

编辑:2017年10月31日

同样的代码/方法也适用于ASP.NET Core2.0。主要的区别在于,在ASP.NET内核中,将web api控制器和Mvc控制器合并到一个控制器模型中。因此返回类型可能是IActionResult或其实现之一(例如:OKObjectResult)

使用

contentType:"application/json"

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

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

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

结果

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;}
}
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;
    }
}
//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 :)
});

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

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

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

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

模型绑定将适用于模型上的平面属性,而不是类型复杂的属性/另一种类型。在我们的示例中,idname属性将正确绑定到参数m,但tags属性将是一个空列表。

$.post("../product/save", model, function (res) {
    //res contains the markup returned by the partial view
    console.log('res', res);
});
 类似资料:
  • 问题内容: 我想将我域的任意对象(例如Person)作为参数传递给.jrxml。 在.jrxml上执行以下操作: 这样的事情可能吗?在哪里可以找到更复杂的教程,这些教程不仅显示传递java.lang.String的内容,还显示更多的内容? 谢谢 问题答案: 是的,您可以传递任何Java对象,但应确保将其导入JRXML。 在jasperReport标记内。您可以使用标记,例如: 但是,您可以使用对象

  • 问题内容: 我有以下内容,但它不起作用,我在stackoverflow上的某个地方读到了它的工作原理,但我似乎无法使其工作..它出错了……我在做错什么吗? 如果我确实传递了这样的数据-它可以工作-所以我知道我的服务正在工作 问题答案: 我相信代码将在对象上调用.value或.toString(),然后通过网络传递。您想传递JSON。 因此,包括JSON JavaScript库 http://www

  • 问题内容: 我有一个对象,其中包含多个通用键值道具,我想将它们传递给一些jsx。像这样: 我希望这可以作为传递单个道具的功能: 这可能吗? 问题答案: 这可能吗? 是的,为什么您认为不可能,但是发送方式不正确。 的含义是: 因此,如果您默认不指定任何值,它将采用。要传递对象,您需要这样编写: 更新: 如果您有一个对象,并且希望将所有属性作为单独的属性传递,则将其编写为:

  • 我有静态方法在我的类 这就是定义 这里用的是 这是我得到的一个错误 E0167类型为“void(TV_DepthCamAgent::)(int count,int copied_file)”的参数与类型为“void()(int,int)”的参数不兼容 错误C3867“TV_DepthCamAgent::progress_callback”:非标准语法;使用' 我做错了什么?

  • 我的RestController中有如下API方法 类如下所示。 在postman中,我传递了一个JSON字符串,如 我得到一个错误说 2021-08-16 18:25:53.953警告4164---[io-8080-exec-10]. w. s. m. s.DefaultHandlerExceptionResolver:已解决[org.springframework.http.converter

  • 问题内容: 我已经成功地建立了一个快速测试,以创建一个“类似REST的”服务,该服务返回序列化为JSON的对象,并且这非常容易且快速(基于本文)。 但是,虽然返回桃子一样的JSON格式的对象很容易,但我还没有看到任何处理非原语输入参数的示例。如何传递复杂的对象作为参数?我正在使用Apache CXF,但也欢迎使用其他框架(例如杰克逊)的示例:) 客户端可能类似于构建javascript对象,将其传