简体   繁体   English

ASP.NET HttpPost方法。 无法正确接收数据

[英]ASP.NET HttpPost method. can't receive data properly

There's the project, that has Node class declared 有一个项目,声明了Node类

public class Node
{
    public string id { get; set; }
    public int group { get; set; }

    public Node( string id, int group)
    {
        this.id = id;
        this.group = group;
    }

    public Node()
    {
    }
}

And method, that has to receive this object and do stuff with it 和方法,必须接收该对象并对其进行处理

[HttpPost]
public IActionResult Create(Node node)
{
    //does stuff here
    return NoContent();
}

One thing I can't understand is how my JSON object has to look like to be correctly deserialized in this method. 我无法理解的一件事是,如何在此方法中正确反序列化我的JSON对象。 I mean I tried to send JSON that looked like this: { "id": "TEST", "group": 1} but thing received object with id = null, group = 0. I don't get it, what do I do wrong? 我的意思是我试图发送看起来像这样的JSON:{“ id”:“ TEST”,“ group”:1},但是接收到的对象的ID为null,group =0。我不明白,我该怎么办?做错了?

By default, the action method model binding in ASP.net is looking for application/x-www-url-formencoded encoded form values. 默认情况下,ASP.net中的操作方法模型绑定正在寻找application/x-www-url-formencoded编码的表单值。

You are POSTing JSON in the body of your request, so you need to use the [FromBody] attribute. 您正在请求的主体中发布JSON,因此您需要使用[FromBody]属性。

[HttpPost]
public IActionResult Create([FromBody] Node node)
{
    //does stuff here
    return NoContent();
}

If you are ever struggling with deserializing a body, try and do it manually to see if you are actually sending it correctly. 如果您在反序列化过程中遇到困难,请尝试手动进行操作,以查看是否正确发送了它。

[HttpPost]
public void Post()
{
    string body = Request.Content.ReadAsStringAsync().Result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM