FromBody string parameter is giving null
By declaring the jsonString parameter with [FromBody]
you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class
public class MyModel
{
public string Key {get; set;}
}
[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] MyModel model)
{
... model.Key....
}
and a sent JSON like
{
key: "value"
}
Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request
in the controller. The HttpContext.Request.Body
property gives you the content stream or you can access the form data via HttpContext.Request.Forms
.
I personally prefer the model binding because of the type safety.
string value is Empty when using FromBody in asp.net web api
Like the doc says :
When a parameter has [FromBody], Web API uses the Content-Type header
to select a formatter.
Only XML and JSON content-types are supported by default. So you need to use application/xml
, application/json
or register a custom IInputFormatter
.
Next, you need to send a content that match the selected content-type.
For json, if the parameter is int
send a number. If it's a class, send a json object. If it's a string, send a json string. Etc.
int => 14
string => "azerty"
class => { "propName" : "value" }
Array => []
... => ...
In your case you should send application/json
content-type and as content :
"Hello string"
And not just
Hello string
Aspnet core json input formatter implementation
Aspnet core xml input formatter implementation
Example: Creating a CSV Media Formatter
Why is my complex [FromBody] parameter null?
In my case there was a problem with the definition of the complex type, I had a parameter marked as string
while it should have been string[]
and so the JSON parsed did not match the model.
The important part though is how I found this out:
When debugging any API method there is the magic ModelState
property.
This property gives you information about any failures that occur while binding the data received to the expected parameters.
e.g:
here we can see the parameter (uploaded
), and the property within that parameter which failed to bind correctly.
Check the definition of that property and you'll probably find an error.
Post parameter is always null
Since you have only one parameter, you could try decorating it with the [FromBody]
attribute, or change the method to accept a DTO with value as a property, as I suggested here: MVC4 RC WebApi parameter binding
UPDATE: The official ASP.NET site was updated today with an excellent explanation: https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1
In a nutshell, when sending a single simple type in the body, send just the value prefixed with an equal sign (=), e.g. body:
=test
Null value when Pass values [FromBody] to post method by Postman plugin
You can't bind a single primitive string using json and FromBody, json will transmit an object and the controller will expect an complex object (model) in turn. If you want to only send a single string then use url encoding.
On your header set
Content-Type: application/x-www-form-urlencoded
The body of the POST request message body should be =saeed
(based on your test value) and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.
Alternate 1
Create a model and use that instead.
Message body value: {"name":"saeee"}
c#
public class CustomModel {
public string Name {get;set;}
}
Controller Method
public HttpResponseMessage Post([FromBody]CustomModel model)
Alternate 2
Pass primitive strings to your post using the URI instead of the message body.
Related Topics
Count the Items from a Ienumerable<T> Without Iterating
Find If Current Time Falls in a Time Range
How to Mock Out the File System in C# for Unit Testing
Centering Controls Within a Form in .Net (Winforms)
Getting Path Relative to the Current Working Directory
How to Programmatically Fill in a Form and 'Post' a Web Page
Tuples( or Arrays ) as Dictionary Keys in C#
C# Dictionary - One Key, Many Values
Write File from Assembly Resource Stream to Disk
How to Force All Referenced Assemblies to Be Loaded into the App Domain
C# Export Private/Public Rsa Key from Rsacryptoserviceprovider to Pem String
Does .Net Have a Way to Check If List a Contains All Items in List B
Merging Multiple PDFs Using Itextsharp in C#.Net
ASP.NET Core 1.0 on Iis Error 502.5
When Should I Use "Using" Blocks in C#
Open File with Associated Application
What's the Difference Between System.Valuetuple and System.Tuple