By default, Web API uses the following rules to bind parameters:
- If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.)
- For complex types, Web API tries to read the value from the message body, using a media-type formatter.
Your parameter is a
string
, so model binding will try to get the value from the URL.
If you add
[FromBody]
to the parameter, it will use the media type formatter to read the parameter from the request body. For a
string
parameter with the
application/json
content type, it expects a single string enclosed in quotes:
POST http:
User-Agent: Fiddler
Host: localhost:5076
Content-Type: application/json
Content-Length: 7
"Alice"
Your body doesn't match that - you're passing in a whole object:
{"userName" : "testUser"}
Rick Strahl posted an approach to bind a string parameter directly to the raw request body back in 2013, which you might be able to adapt:
Accepting Raw Request Body Content with ASP.NET Web API - Rick Strahl's Web Log[
^]
Otherwise, the simplest solution is probably to create a class to represent your parameter:
public class TestUserParameters
{
public string UserName { get; set; }
}
...
[HttpPost("TestUser")]
public async Task<IActionResult> TestUserAsync(TestUserParameters model) { ... }