我需要使用REST API C#更新SharePoint在线文档库属性。但我一直收到400(错误的请求)错误

时间:2018-06-15 05:56:35

标签: c# rest api sharepoint-online

我的网址是正确的。当我使用浏览器进行搜索时,它会给我文件。

https://sharepoint.com/sites/sitecollection/_api/web/GetFileByServerRelativeUrl('/sites/sitecollection/DocumentLibraryName/file.txt')/ListItemAllFields

我的更新方式是错误的吗?

System.Net.HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;

wreq.UseDefaultCredentials = false;          
wreq.Credentials = credential;
wreq.CookieContainer = GetO365CookieContainer(credential, webUrl);
wreq.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";

string formDigest = GetFormDigestValue(webUrl, credential, wreq.CookieContainer);

wreq.Method = "POST";
wreq.Accept = "application/json;odata=verbose";
wreq.ContentType = "application/json;odata=verbose";
wreq.Headers.Add("X-HTTP-Method", "MERGE");
wreq.Headers.Add("IF-MATCH", "*");
wreq.Headers.Add("X-RequestDigest", formDigest);


string stringData = "{'__metadata': { 'type': 'SP.Data.DocumentsItem' }, 'Description': 'Added'}";
byte[] byteArray = Encoding.UTF8.GetBytes(stringData);
wreq.ContentLength = stringData.ToString().Length;
StreamWriter writer = new StreamWriter(wreq.GetRequestStream());
writer.Write(stringData);
writer.Flush();

1 个答案:

答案 0 :(得分:0)

检查Vadim Gremyachev here共享的代码,希望它有用。

public class Program
{
    public static void Main(string[] args)
    {
        var smartLightBulb = new SmartLightBulb()
        {
            DeviceType = "deviceType",
            Model = "model"
        };
        Output(smartLightBulb);
    }

    public static void Output(Device device)
    {
        var smartLightBulb = (device as SmartLightBulb);
        if(smartLightBulb != null)
        {
            Console.WriteLine(smartLightBulb.Model);
        }
    }
}

public class Device
{
    public string DeviceType { get; set; }
}

public class SmartLightBulb : Device
{
    public string Model { get; set; }
}