Buda Gavril Buda Gavril - 18 days ago 5
C# Question

web api: action parameter is null

I have a simple web api but when I test it with Postman, the method parameter is null. I've looked and over other questions with similar title but I haven't found an answer.

Here is my controller action:

[HttpPost]
public Member Create([FromBody] string payload)
{
var s = Request.Content.ReadAsStringAsync();

if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}

Console.WriteLine(payload);
Console.WriteLine(s);

return null;
}


And here is my postman configuration:
enter image description here

In the headers tab I've added
content-type
to be
application/json
.

when I'm debugging this, the
payload
variable is allways
null
and the string
s
contains something like

Id = 98, Status = RanToCompletion, Method = "{null}", Result = ""


So what am I doing wrong?

Answer

You should wrap your string in model (object):

class Model
{
    public string payload {get;set;}
}

[HttpPost]
public async Task<Member> Create([FromBody] Model model) // wrap Member in Task and add async keyword
{
    var s = await Request.Content.ReadAsStringAsync(); // add await here

    if (model.payload == null)
    {
        throw new ArgumentNullException(nameof(model.payload));
    }

    Console.WriteLine(model.payload);
    Console.WriteLine(s);

    return null;
}

If you don't want to use model, try to send only plain string, like "some payload", do not wrap it in json.

Comments