Noah Noah - 4 months ago 35
JSON Question

SharePoint 2013 REST API: Updating File Metadata

I am attempting to modify the metadata of a file that has just been uploaded.

using (HttpClient client = new HttpClient(new HttpClientHandler { Credentials = _authenticator.Credential }))
{
client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", _authenticator.Token);
client.BaseAddress = _authenticator.Endpoint;
client.DefaultRequestHeaders.Add("IF-MATCH", "*");

string cmd = String.Format("_api/web/lists/GetByTitle('Drop Off Library')/items({0})", file.Id);

string jsonString = JsonConvert.SerializeObject(file);
StringContent test = new StringContent(jsonString, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(cmd, test);
}


I successfully GET the file's metadata above, and store it in a SharePoint file model of my own creation. I modify one of the file's metadata fields, and then attempt to merge the deserialized object back in. This has been resulting in a 400 Bad Request error. Any ideas of why this might be happening?

Answer

The solution would be to replace the lines:

string jsonString = JsonConvert.SerializeObject(file);
StringContent test = new StringContent(jsonString, Encoding.UTF8, "application/json");

with

var test = new StringContent(JsonConvert.SerializeObject(payload));
test.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");

since in your case the invalid Content-Type header is generated.

enter image description here

See JSON Light support in REST SharePoint API released for a list of supported formats.

Comments