I have two actions
[HttpPost("MyFromForm")]
public async Task<IActionResult> MyFromForm([FromForm] RequestExample request)
{
return new OkObjectResult(request);
}
[HttpPost("MyFromBody")]
public async Task<IActionResult> MyFromBody([FromBody] RequestExample request)
{
return new OkObjectResult(request);
}
The class contains only one property of Dictionary type
public class RequestExample
{
public Dictionary<string, string> DeviceDetails { get; set; }
}
Request In case I send the data using swagger to these methods, The method having FromBody is working but the method having FromForm is not working .
1. Using: FromBody, I am able to receive the dictionary in the request.
{
"deviceDetails": {
"additionalProp1": "string",
"additionalProp2": "string",
"additionalProp3": "string"
}
}
Curl Request:
curl -X POST "http://localhost:7002/MyItems/MyFromBody" -H "accept: */*" -H "Content-Type: application/json" -d "{\"deviceDetails\":{\"additionalProp1\":\"string\",\"additionalProp2\":\"string\",\"additionalProp3\":\"string\"}}"
On the server-side, we are able to receive the data in the dictionary object.
2. Using: FromForm, I am not able to receive the dictionary in the request
Curl Request :
curl -X POST "http://localhost:7002/Abc/MyFromForm" -H "accept: */*" -H "Content-Type: multipart/form-data" -F "DeviceDetails={
"additionalProp1": "string",
"additionalProp2": "string",
"additionalProp3": "string"
}"
The output is empty.
Question: Why I am not able to receive the object in FromForm type of request?
CodePudding user response:
Seems you didn't change the Request body type. The FromForm
attribute is for incoming data from a submitted form sent by the content-type application/x-www-form-urlencoded
while the FromBody
will parse the model the default way, which in most cases are sent by the content-type application/json
, from the request body.
CodePudding user response:
You are not sending valid X FORM URL ENCODED data:
And example is this:
curl -d "additionalProp1=nice&additionalProp2=woohoo" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:7002/Abc/MyFromForm
you are trying to send a json string as a form dictionary.
Form enconded values should be separated by ampersands without quotes on the keys or values.
Also using multipart/form-data is not to send form data, at least not generally speaking. multipart/form-data is used to upload files or binary data not text fields.
You should use -d instead of -F and Content-Type: application/x-www-form-urlencoded instead of multipart/form-data