I'm currently working on an .NET Framework 4.7.2 application. I need to call an Web API Controller from within my C# code.
I'm updating a dynamic object, I cannot create any viewmodel.The dynamic object has the following structure, and will be filled dynamically with different keys:
List<KeyValuePair<int,Dictionary<string, object>>>
The calling code looks like that:
var task = Task.Run(async () => await UpdateMyInformation(myDynamicObject));
var test = task.Result;
The method implementation:
private async Task<dynamic> UpdateMyInformation(dynamic data)
{
var content = new StringContent(JsonConvert.SerializeObject(data).ToString(),
Encoding.UTF8, "application/json");
var baseUrl = "http://localhost:1234/api/MyInformationController";
using (HttpClient client = new HttpClient())
{
var response = await client.PutAsync(baseUrl, content);
response.EnsureSuccessStatusCode();
var result = response.Content.ReadAsStringAsync().Result;
return result;
}
}
The API Controller looks like that:
public class MyInformationController : ApiController
{
[HttpPut]
public async Task<dynamic> Put(dynamic myData)
{
// I need to parse data and return the new dynamic object
// Manipulate myData according to a given logic
return myData;
}
}
I can receive the data in my controller action, my question is: Should I use dynamic to get a JSON object into my controller?
What would perhaps be a better approach to solve this?
I would use JObject instead of dynamic.
public class MyInformationController : ApiController
{
[HttpPut]
public async Task<dynamic> Put(JObject myData)
{
// I need to parse data and return the new dynamic object
// Manipulate myData according to a given logic
return myData;
}
}
By using the JObject, you can access the properties in the object based on the keys. Please see the docs for more information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With