我正在尝试使用REST api和HttpClient更新SharePoint 2013列表标题。我有以下代码,但StatusCode正在返回BadRequest。
private async void UpdateTitle()
{
string webUrl = http://server;
Uri uri = new Uri(webUrl + "/_api/web/lists/GetByTitle('Old')");
//start replacement
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(httpClientHandler);
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
string digest = await GetFormDigest("http://devsp13.dev.local/_api/contextinfo");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "Merge");
client.DefaultRequestHeaders.Add("IF-MATCH", "*");
HttpContent content = new StringContent("{ '__metadata': { 'type': 'SP.List' }, 'Title': 'NewTitle' }");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();}
我猜我在形成HttpClient时错过了一些东西,但我很难看到什么。非常感谢任何帮助。
干杯,
杰夫
答案 0 :(得分:0)
尝试将Accept添加到HttpClient DefaultRequestHeaders并在HttpContent Headers上设置ContentType。这对我有用。
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", GetFormDigest());
client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE");
client.DefaultRequestHeaders.Add("IF-MATCH", "*");
HttpContent content = new StringContent(metadataString);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();