How to Post JSON data to a Web API using HttpClient
10,524
Solution 1
Your obj right at the start isn't needed. That is nesting f inside another object.
var obj = new
{
f = new File
{
Description = description,
File64 = Convert.ToBase64String(fileContent),
FileName = fileName,
VersionName = versionName,
MimeType = mimeType
},
}
Change to
var f = new File
{
Description = description,
File64 = Convert.ToBase64String(fileContent),
FileName = fileName,
VersionName = versionName,
MimeType = mimeType
};
Then just serialize f.
Solution 2
I think there is a problem on this part of your code
var obj = new
{
f = new File
{
Description = description,
File64 = Convert.ToBase64String(fileContent),
FileName = fileName,
VersionName = versionName,
MimeType = mimeType
},
}
As this will be serialized differently from what you really needed. Try this instead
var obj = new File
{
Description = description,
File64 = Convert.ToBase64String(fileContent),
FileName = fileName,
VersionName = versionName,
MimeType = mimeType
}
Author by
Ben Temple-Heald
Updated on June 05, 2022Comments
-
Ben Temple-Heald almost 2 years
I have the following code, basically it takes in a dynamic object (in this case of type file) and using the
HTTPClient
class tries to a POST to aWebAPI controller
, the issue I am having is that the controller is always gettingNULL
for the values on my[FromBody]
parameter.Code
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); }
Controller
[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 }
Model
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; } }
The model is shared on both the
WebAPI
and the client app.Any help on why this is failing would be much appreciated, been going around in circles for a while now.