简体   繁体   English

C#使用REST API将项目添加到Sharepoint列表

[英]C# Add item to Sharepoint list using REST API

I would like to add an item to a list in sharepoint using below code: 我想使用以下代码将项目添加到共享点的列表中:

protected string httpGetPost(string getPostMode, string url, string dataToPost = "")
{
    HttpWebRequest endpointRequest = (HttpWebRequest)WebRequest.Create(url);
    endpointRequest.Method = getPostMode;

    var credentialCache = new CredentialCache();
    credentialCache.Add(
      new Uri(endpointRequest.RequestUri.GetLeftPart(UriPartial.Authority)), // request url's host
      "Digest",  // authentication type 
      new NetworkCredential(userName, password) // credentials 
    );
    endpointRequest.Credentials = credentialCache;

    endpointRequest.Accept = "application/json;odata=verbose";
    endpointRequest.ContentType = "application/json;odata=verbose";

    if (!string.IsNullOrEmpty(dataToPost))
    {
        using (Stream dataStream = endpointRequest.GetRequestStream())
        {
            byte[] bs = Encoding.ASCII.GetBytes(dataToPost);
            dataStream.Write(bs, 0, bs.Length);
        }
    }
    using (var resp = endpointRequest.GetResponse())
    {
        var html = new StreamReader(resp.GetResponseStream()).ReadToEnd();
        return html;
    }
}

And call the above method using below code: 并使用以下代码调用上述方法:

httpGetPost("POST", url, "{\"__metadata\": { \"type\": \"SP.Data.Test_x0020_ListListItem\" }, \"Title\": \"Test\", \"Column B\", \"BBB\"}");

Here's the data I'm posting: 这是我要发布的数据:

{"__metadata": { "type": "SP.Data.Test_x0020_ListListItem" }, "Title": "Test", "Column B", "BBB"} {“ __metadata”:{“ type”:“ SP.Data.Test_x0020_ListListItem”},“ Title”:“ Test”,“ B列”,“ BBB”}

I've took a look at this website https://msdn.microsoft.com/en-us/library/office/dn292552.aspx , but the authorization is different, it's using an accesstoken, but here's the problem: 我看过这个网站https://msdn.microsoft.com/en-us/library/office/dn292552.aspx ,但是授权不同,它使用的是访问令牌,但这是问题所在:

In this website: http://sharepoint.stackexchange.com/questions/69617/sharepoint-2013-oauth-url-to-get-token , it saids I can't get the accesstoken, so I used username and password to login the sharepoint, but here comes another problem: 在此网站中: http://sharepoint.stackexchange.com/questions/69617/sharepoint-2013-oauth-url-to-get-token ://sharepoint.stackexchange.com/questions/69617/sharepoint-2013-oauth-url-to-get-token,它说我无法获取访问令牌,因此我使用用户名和密码登录共享点,但这又带来了另一个问题:

A System.Net.WebException is thrown in var resp = endpointRequest.GetResponse() , the error is saying The remote server returned an error: (403) Forbidden. var resp = endpointRequest.GetResponse()引发了System.Net.WebException ,错误是说The remote server returned an error: (403) Forbidden.

The account is a domain admin as well as a sharepoint admin. 该帐户是域管理员和共享点管理员。

Why I'm still getting the 403 error? 为什么我仍然收到403错误?

For some reasons, I can only use the REST API to communicate with sharepoint. 由于某些原因,我只能使用REST API与共享点进行通信。

Here is a slightly different method to achieve your goals. 这是实现目标的略有不同的方法。 Some of the objects are specific to Store Apps in this example, but they can all easily be replaced with other values in a standard app. 在此示例中,某些对象特定于Store Apps,但是在标准应用程序中,它们可以很容易地用其他值替换。

 public string digest()
 {
 String retVal = "";
 try
 {
 string url = "https://YourSite.com/";
 HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
 client.BaseAddress = new System.Uri(url);
 string cmd = "_api/contextinfo";
 client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
 client.DefaultRequestHeaders.Add("ContentType", "application/json");
 client.DefaultRequestHeaders.Add("ContentLength", "0");
 StringContent httpContent = new StringContent("");
 var response = client.PostAsync(cmd, httpContent).Result;
 if (response.IsSuccessStatusCode)
 {
 string content = response.Content.ReadAsStringAsync().Result;
 JsonObject val = JsonValue.Parse(content).GetObject();
 JsonObject d = val.GetNamedObject("d");
 JsonObject wi = d.GetNamedObject("GetContextWebInformation");
 retVal = wi.GetNamedString("FormDigestValue");
 }
 }
 catch
 { }
 return retVal;
 }

 FileOpenPicker picker = new FileOpenPicker();
 picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 picker.ViewMode = PickerViewMode.Thumbnail;
 // Filter to include a sample subset of file types.
 picker.FileTypeFilter.Clear();
 picker.FileTypeFilter.Add(".bmp");
 picker.FileTypeFilter.Add(".png");
 picker.FileTypeFilter.Add(".jpeg");
 picker.FileTypeFilter.Add(".jpg");
 // Open the file picker.
 StorageFile path = await picker.PickSingleFileAsync();
 if (path != null)
 {
 string url = "https://YourSite.com/Subsite/";
 HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
 client.BaseAddress = new System.Uri(url);
 client.DefaultRequestHeaders.Clear();
 client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
 client.DefaultRequestHeaders.Add("X-RequestDigest", digest());
 client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
 client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true");
 IRandomAccessStream fileStream = await path.OpenAsync(FileAccessMode.Read);
 var reader = new DataReader(fileStream.GetInputStreamAt(0));
 await reader.LoadAsync((uint)fileStream.Size);
 Byte[] content = new byte[fileStream.Size];
 reader.ReadBytes(content);
 ByteArrayContent file = new ByteArrayContent(content);
 HttpResponseMessage response = await client.PostAsync("_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?@TargetLibrary='Project Photos'&@TargetFileName='TestUpload.jpg'", file);
 response.EnsureSuccessStatusCode();
 if (response.IsSuccessStatusCode)
 { }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM