自从升级到RC的WebAPI,我有一些真正奇怪的问题时调用POST在我的WebAPI。 我甚至回到了在新项目上生成的基本版本。所以:

public void Post(string value)
{
}

提琴手喊道:

Header:
User-Agent: Fiddler
Host: localhost:60725
Content-Type: application/json
Content-Length: 29

Body:
{
    "value": "test"
}

当我调试时,字符串“value”永远不会被赋值。它总是NULL。 有人有这个问题吗?

(我第一次看到这个问题是在一个更复杂的类型上)

这个问题不仅仅局限于ASP。在asp.net MVC 4中,同样的问题出现在一个新的ASP。NET MVC 3项目后RC安装


当前回答

在WebAPI中传递一个参数是正确的。post(url, {": productId}

并在行动中捕捉它[HttpPost] public ShoppingCartAddRemoveViewModel Delete([FromBody]字符串值)

关键是要使用“价值”这个神奇的词。它也可以是int型,或者一些基本类型。 无论是内容类型还是标题更正 混乱是这段代码不能在mvc post action中工作。

其他回答

我尝试了这个帖子中的许多答案,但没有一个对我有用。然后我在一个类似的帖子中看到了这个答案:https://stackoverflow.com/a/40853424/2120023,他提到HttpContext. request . body,所以另一个搜索,我发现这个https://stackoverflow.com/a/1302851/2120023给了我HttpContext。当前,所以我终于得到了这个工作使用:

HttpContext.Current.Request.Form.Get("value");

邮差的要求:

curl --location --request POST 'https://example.com/token' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'value=test'

这招对我很管用:

Create a C# DTO class, with a property for every attribute you want to pass from jQuery/Ajax public class EntityData { public string Attr1 { get; set; } public string Attr2 { get; set; } } Define the web api method: [HttpPost()] public JObject AddNewEntity([FromBody] EntityData entityData) { Call the web api as such: var entityData = { "attr1": "value1", "attr2": "value2" }; $.ajax({ type: "POST", url: "/api/YOURCONTROLLER/addnewentity", async: true, cache: false, data: JSON.stringify(entityData), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { ... } });

我也有同样的问题,并发现当将内容类型更改为“application/json”时并没有解决这个问题。然而“application / json;charset = utf - 8”工作。

API:

[HttpPost]
public bool UpdateTicketStatus(Ticket t)
{    
    string Id=t.Id;
}

模型:

public class Ticket
{
    public int Id { get; set; }
    public string AssignedTo { get; set; }
    public string State { get; set; }
    public string History { get; set; }
}

使用Post man工具将内容发送为json和原始数据,如下所示。它的工作原理

{ “Id”:“169248”, “AssignedTo”:“xxxx”, “状态”:“承诺”, “历史”:“test1” }

请确保您已启用Cors。

[EnableCors(origins: "*", headers: "*", methods: "*")]
    public class TicketController : ApiController
    {
}

在ASP中也遇到过类似的问题。NET Core和另一个可能的原因是ASP。NET绑定(沉默)失败,由于各种原因,如发送null被绑定到一个非null属性:

{
    "prop1":1139357,
    "prop2":1139356,

    "items":[
        {"key":"15","someprop":34,"notnullprop":null},
        {"key":"16","someprop":34,"notnullprop":null},
        {"key":"22","someprop":34,"notnullprop":null}]
}

在这种情况下,不会抛出异常,整个模型将为null,即使这种情况发生在对象层次结构的深处。