Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute routing for POST in C# .NET

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){}
like image 257
Amarsh Avatar asked Sep 03 '25 03:09

Amarsh


1 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);
}
like image 145
Nkosi Avatar answered Sep 04 '25 17:09

Nkosi