2016-07-06 76 views
3

我有以下代碼,基本上它需要一個動態對象(在這種情況下是類型文件)並使用HTTPClient類嘗試POST到WebAPI controller,問題我得到的是控制器總是得到NULL爲我的[FromBody]參數上的值。如何使用HttpClient將JSON數據發佈到Web API

代碼
var obj = new 
     { 
      f = new File 
      { 
       Description = description, 
       File64 = Convert.ToBase64String(fileContent), 
       FileName = fileName, 
       VersionName = versionName, 
       MimeType = mimeType 
      }, 
     } 

var client = new HttpClient(signingHandler) 
{ 
    BaseAddress = new Uri(baseURL + path) //In this case v1/document/checkin/12345 
}; 

client.DefaultRequestHeaders.Accept.Clear(); 
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));       

HttpResponseMessage response; 
action = Uri.EscapeUriString(action); 

//Obj is passed into this, currently it is of type File 
var content = new StringContent(JsonConvert.SerializeObject(obj).ToString(), 
      Encoding.UTF8, "application/json"); 

response = client.PostAsync(action, content)).Result; 
if (response.IsSuccessStatusCode) 
{  
    var responseContent = response.Content;     
    string responseString = responseContent.ReadAsStringAsync().Result; 
    return JsonConvert.DeserializeObject<T>(responseString); 
} 

控制器
[HttpPost] 
[Route("v1/document/checkin/{id:int}")] 
public void Checkin_V1(int id, [FromBody] File f) 
{ 
     //DO STUFF - f has null on all of its properties 
} 

模型
public class File 
{ 
    public string FileName { get; set; } 
    public string VersionName { get; set; } 
    public string Description { get; set; } 
    public string MimeType { get; set; } 
    public byte[] Bytes { get; set;} 
    public string File64 { get; set; } 
} 

該模型是在WebAPI和客戶端應用程序兩者共享。

任何幫助,爲什麼這是失敗的,將不勝感激,一直在繞圈子一段時間了。

回答

7

您的obj在開始時不需要。這是將f嵌套在另一個對象內部。

var obj = new 
    { 
     f = new File 
     { 
      Description = description, 
      File64 = Convert.ToBase64String(fileContent), 
      FileName = fileName, 
      VersionName = versionName, 
      MimeType = mimeType 
     }, 
    } 

更改爲

var f = new File 
{ 
    Description = description, 
    File64 = Convert.ToBase64String(fileContent), 
    FileName = fileName, 
    VersionName = versionName, 
    MimeType = mimeType 
}; 

然後,只需序列F。

+0

工程就像一個魅力,謝謝。 –

4

我覺得這是對你的代碼

var obj = new 
    { 
     f = new File 
     { 
      Description = description, 
      File64 = Convert.ToBase64String(fileContent), 
      FileName = fileName, 
      VersionName = versionName, 
      MimeType = mimeType 
     }, 
    } 

由於此,這部分問題將被從你真正需要什麼不同的序列化。 試試這個,而不是

var obj = new File 
     { 
      Description = description, 
      File64 = Convert.ToBase64String(fileContent), 
      FileName = fileName, 
      VersionName = versionName, 
      MimeType = mimeType 
     } 
相關問題