Ben Temple-Heald Ben Temple-Heald - 4 months ago 20
JSON Question

How to Post JSON data to a Web API using HttpClient

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 a WebAPI controller, the issue I am having is that the controller is always getting NULL 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.

Answer

You 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.

Comments