1

我正在尝试使用 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 时遗漏了一些东西,但我很难看到什么。任何帮助深表感谢。

干杯,

杰夫

4

1 回答 1

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();
于 2014-03-17T15:32:42.313 回答