Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api FromBody is null from web client

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;
    }
}
like image 755
Arbejdsglæde Avatar asked Apr 17 '14 14:04

Arbejdsglæde


1 Answers

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.

like image 122
jensendp Avatar answered Oct 02 '22 06:10

jensendp