We have below API method which I need to debug. The API is being called from a web which at this moment I dont have access to so dont know whats the exact format of params being passed.
In the mean time I want construct a json so that I can pass to this method and debug. But whatever I pass its always null. Could you please share what am I doing wrong
[HttpPost]
public IActionResult PostData([FromBody] List<Dictionary<string, string>> data)
{
//parse data here
}
The data param always comes out to be null, when I am passing below json. Since its null I cannot proceed further.
My swagger shows this is whats being expected but when I pass the same, it shows data param to be null:
[
{
"additionalProp1": "string",
"additionalProp2": "string",
"additionalProp3": "string"
}
]
I have tried to modify the above json but keeps on saying null. Any input what the correct json would be
CodePudding user response:
if you don't know what to expect, the safest way is
[HttpPost]
public IActionResult PostData([FromBody] JToken data)
{
//if you don't know
var json=data.ToString();
// or
var prop1 = (string)data[0]["additionalProp1"];
// or it seems to me that you know what to expect
Dictionary<string,string>[] dict = data.ToObject<Dictionary<string,string>[]>();
}
the code will be working if you use Newtonsoft.Json
using Newtonsoft.Json.Serialization;
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
but I guess you can find analogical code for text.json
PS
Your action with a dictionary should be working too. I am afraid that you are creating a wrong http request or http request body. Post the code are you using
CodePudding user response:
You could try JsonConvert.DeserializeObject<List<Dictionary<string, string>>>
(data)
It sometimes works when FromBody
attribute doesn't.