Attribute routing for POST in C# .NET

Viewed 1861

The following give me args=null when I POST with a body {"args": 222}. How can I get the member of the body into my variable args (or the entire body into a variable body)

[HttpPost("{className}/{methodName}")]
public ActionResult<string> Post(string className, string methodName, string args){}
2 Answers

The JSON

{"args": 222}

implies that args is a number.

Create a model to hold the expected data

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

Update the action to explicitly expect the data from the request body

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