简体   繁体   English

Web Api FromBody从Web客户端为空

[英]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. 您好我想通过Web api控制器中的body变量从C#客户端调用Web Api方法始终为null。 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. 您传入的是匿名类型的JSON序列化字符串表示形式,因此Web Api中的反序列化过程对您不利。 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. 尝试将SavImage方法上的类型更改为动态。 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. 不幸的是,您将无法使用intellisense来获取您的房产。 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. 这会让这更容易一些。

在body中传递的字符串值可能需要以=符号为前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM