Web Api FromBody is null from web client

折月煮酒 提交于 2019-12-10 02:46:53

问题


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;
    }
}

回答1:


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.




回答2:


The string value passed in the body probably needs to be prefixed with the = sign.



来源:https://stackoverflow.com/questions/23135403/web-api-frombody-is-null-from-web-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!