Reputation: 21627
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:
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?
Upvotes: 1
Views: 1145
Reputation: 12171
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
.
Upvotes: 0
Reputation: 1522
Buda,
HttpContent.ReadAsStringAsync
returns a Task<string>
, hence the value of the s
string.
You have to update your action to make it async:
[HttpPost]
public async Task<Member> Create([FromBody] string payload)
{
var s = await Request.Content.ReadAsStringAsync();
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
Console.WriteLine(payload);
Console.WriteLine(s);
return null;
}
Upvotes: 1