Hello I would like to call Web Api method from C# client by my body variable in web api controller is null all the time. How to set it correct ? client side:
IFileService imgService = new ImageServiceBll();
var image = System.Drawing.Image.FromFile(serverFile);
var dataImage = imgService.ImageToBase64(image, System.Drawing.Imaging.ImageFormat.Png);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://site.local/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var data = new
{
imageData = dataImage,
version = version
};
HttpResponseMessage response = await client.PostAsJsonAsync("api/contenttool/SaveImage", data);
if (response.IsSuccessStatusCode)
{
Uri gizmoUrl = response.Headers.Location;
}
}
Server Side:
public class ContentToolController : ApiController
{
public IFileService FileService { get; set; }
// POST api/contenttool
public string SaveImage([FromBody]string data)
{
JObject jObject = JObject.Parse(data);
JObject version = (JObject)jObject["version"];
return "-OK-" + version;
}
}
I think it has more to do with the fact that you technically aren't passing in a string. You are passing in a JSON serialized string representation of an anonymous type, so the deserialization process in the Web Api is working against you. By the time your request gets to the controller and that method, it isn't a string anymore. Try changing your type on the SavImage method to be dynamic. Like this:
public string SavImage([FromBody]dynamic data)
{
JObject jObject = JObject.Parse(data);
JObject version = (JObject)jObject["version"];
return "-OK-" + version;
}
Unfortunately at that point you won't be able to use intellisense to get your properties out. You will have to get the data out of the dynamic type via a dictionary.
Dictionary<string, object> obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(Convert.ToString(data));
Of course your other option would be to use an actual type that is shared between the client and the server. That would make this a bit easier.
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