C#.NET中POST的属性路由

问题描述 投票:1回答:2

以下给我args=null当我POST与身体{"args": 222}。我怎样才能将身体的成员变成我的变量args(或整个身体变成body变量)

[HttpPost("{className}/{methodName}")]
public ActionResult<string> Post(string className, string methodName, string args){}
c# asp.net-core attributerouting asp.net-core-routing
2个回答
3
投票

JSON

{"args": 222}

暗示args是一个数字。

创建一个模型来保存预期的数据

public class Data {
    public int args { get; set; }
}

更新操作以明确期望来自请求正文的数据

[HttpPost("{className}/{methodName}")]
public ActionResult<string> Post(string className, string methodName, [FromBody] Data body) {
    if(ModelState.IsValid) {
        int args = body.args
        //...
    }
    return BadRequest(ModelState);
}

0
投票

如果要使用属性路由,则必须在WebAPIConfig上启用属性路由。每个动作PUT,GET,POST等都有一个[Route()]。

我所看到你做的是传统路由。

有关属性路由的更多信息,我建议你通过这个https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

© www.soinside.com 2019 - 2024. All rights reserved.