我正在尝试使用rest api在线更新sharepoint中的多项选择字段。我收到401错误请求错误。
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("XXXXX/_api/web/getfilebyserverrelativeurl('/sites/Sample/TestDoc.docx')/ListItemAllFields/");
string stringData =
@"{'__metadata': { 'type':'SP.ListItem' },
'TestColumn': { '__metadata': { 'type' : 'Collection(Edm.String)', results: ['Test1']}}}";
request.ContentLength = stringData.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(stringData);
writer.Flush();
response = (HttpWebResponse)request.GetResponse();
任何帮助?
答案 0 :(得分:2)
在您的示例中,有效负载很可能无效:
string stringData =
@"{'__metadata': { 'type':'SP.ListItem' },
'TestColumn': { '__metadata': { 'type' : 'Collection(Edm.String)', results: ['Test1']}}}";
点是SP.ListItem
类型对应Generic
列表,在您的示例中,它是 Documents 库。
因此,需要提供有效 实体类型名称,您可以使用以下端点来确定metadata type
:
端点:
Url: /_api/lists/getbytitle('<list title>')?$select=ListItemEntityTypeFullName
Method: GET
其次,Update操作需要使用request指定以下属性:
POST
动词X-HTTP-Method
标头,其值为MERGE。If-Match
标头,其中包含实体原始ETag的值。您可以参考this post了解更多详情。
最后但并非最不重要的是,需要指定Content-Type
和Accept
个请求标头(有关详细信息,请点击this article),例如:
request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json;odata=verbose";
以下示例对其进行了总结,并演示了如何更新多选字段值:
var requestUrl = $"{webUrl}/_api/web/getfilebyserverrelativeurl('{fileUrl}')/ListItemAllFields";
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Credentials = GetCredentials(userName, password);
request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json;odata=verbose";
request.Method = "POST";
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
request.Headers.Add("X-RequestDigest", formDigestVal);
request.Headers.Add("X-HTTP-Method", "MERGE");
request.Headers.Add("If-Match", "*");
var payload = @"{
'__metadata': { 'type':'SP.Data.Shared_x0020_DocumentsItem' },
'<ColumnName>': { '__metadata': { 'type' : 'Collection(Edm.String)'}, results: ['Val1']}
}";
request.ContentLength = payload.Length;
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(payload);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();