2017-08-28 36 views
1

我執行下面的代碼:用Sharepoint Rest API創建列表項;結果是400錯誤的請求

using Microsoft.SharePoint.Client; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 
using System; 
using System.Collections.Generic; 
using System.Net; 
using System.Security; 
using System.Text; 

namespace Sharepoint_sandbox { 
    class Program { 
     private static CookieContainer GetO365CookieContainer (SharePointOnlineCredentials credentials, string targetSiteUrl){ 
     CookieContainer container = null; 

     Uri targetSite = new Uri (targetSiteUrl); 
     string cookieString = credentials.GetAuthenticationCookie (targetSite); 
     if (cookieString != null) { 
      string trimmedCookie = cookieString.TrimStart ("SPOIDCRL=".ToCharArray()); 
      container = new CookieContainer(); 
      container.Add (new Cookie ("SPOIDCRL", trimmedCookie, string.Empty, targetSite.Authority)); 
     } 

     return container; 
     } 

     private static SharePointOnlineCredentials GetO365Credentials (string userName, string password) { 
     SecureString securePassword = new SecureString(); 
     foreach (char c in password.ToCharArray()) 
      securePassword.AppendChar (c); 

     return new SharePointOnlineCredentials (userName, securePassword); 
     } 

     private static string GetFormDigest (string siteUrl, ICredentials credentials, CookieContainer cc) { 
     string formDigest = null; 

     string resourceUrl = siteUrl + "/_api/contextinfo"; 
     HttpWebRequest httpWebRequest = HttpWebRequest.Create (resourceUrl) as HttpWebRequest; 
     httpWebRequest.Credentials = credentials; 
     httpWebRequest.CookieContainer = cc; 
     httpWebRequest.Timeout = 10000; 
     httpWebRequest.Method = "POST"; 
     httpWebRequest.ContentType = "application/json; odata=verbose"; 
     httpWebRequest.Accept = "application/json;odata=verbose"; 
     httpWebRequest.ContentLength = 0; 
     httpWebRequest.ContentType = "application/json"; 
     string result; 
     using (WebResponse webResponse = httpWebRequest.GetResponse()) { 
      using (System.IO.StreamReader sr = new System.IO.StreamReader (webResponse.GetResponseStream())) { 
       result = sr.ReadToEnd(); 
      } 
     } 
     var dObject = (JObject)JsonConvert.DeserializeObject (result); 
     foreach (var item in dObject["d"].Children()){ 
      formDigest = item.First["FormDigestValue"].ToString(); 
     } 

     return formDigest; 
     } 

     private static Tuple<string, List<string>> CreateListItem (string site, string userName, string password, string resourceUrl, string content) { 
     HttpWebRequest httpWebRequest = HttpWebRequest.Create (resourceUrl) as HttpWebRequest; 
     httpWebRequest.UseDefaultCredentials = false; 
     SharePointOnlineCredentials credentials = GetO365Credentials (userName, password); 
     httpWebRequest.Credentials = credentials; 
     httpWebRequest.CookieContainer = GetO365CookieContainer (credentials, site); 
     string formDigest = GetFormDigest (site, credentials, httpWebRequest.CookieContainer); 
     httpWebRequest.Method = "POST"; 
     httpWebRequest.Headers.Add ("X-RequestDigest", formDigest); 
     httpWebRequest.Timeout = 10000; 
     httpWebRequest.ContentType = "application/json; odata=verbose"; 
     httpWebRequest.Accept = "application/json; odata=verbose"; 
     httpWebRequest.ContentLength = 0; 

     List<string> errorMessages = new List<string>(); 
     string response = ""; 
     try { 
      byte[] binary = Encoding.Unicode.GetBytes(content); 
      httpWebRequest.ContentLength = binary.Length; 
      using (System.IO.Stream requestStream = httpWebRequest.GetRequestStream()) { 
       requestStream.Write (binary, 0, binary.Length); 
      } 

      using (WebResponse webResponse = httpWebRequest.GetResponse()) { 
       using (System.IO.StreamReader sr = new System.IO.StreamReader (webResponse.GetResponseStream())) { 
        response = sr.ReadToEnd(); 
       } 
      } 
     } 
     catch (WebException e) { 
      errorMessages.Add (e.Message); 
      if (e.Response != null && e.Response.GetResponseStream() != null) { 
       using (System.IO.StreamReader sr = new System.IO.StreamReader (e.Response.GetResponseStream())) { 
        errorMessages.Add (sr.ReadToEnd()); 
       } 
      } 
     } 

     return new Tuple<string, List<string>> (response, errorMessages); 
     } 

     static void Main (string[] args) { 
     string site = "https://*******"; 
     string user = "******"; 
     string password = "******"; 

     string resourceUrl = site + "/_api/Web/Lists(guid'0818cf14-4028-4c7d-adbc-489adb1c0cb4')/Items"; 
     string content = "{ '__metadata': { 'type':'SP.Data.Test_x005f_1ListItem' }, 'Title': 'TestItem'}"; 

     Tuple<string, List<string>> result = CreateListItem (site, user, password, resourceUrl, content); 

     Console.Write (result.Item1 + "\n" + string.Join ("\n", result.Item2)); 
     Console.ReadKey(); 
     } 
    } 
} 

結果是:

A távoli kiszolgáló a következő hibát küldte vissza: (400) Hibás kérelem. 
{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"hu-HU","value":"Invalid JSON. The property name '' is not valid. The name of a property cannot be empty."}}} 

英語匈牙利文: 遠程服務器返回錯誤:(400)錯誤的請求。

我不想忽略哪個屬性是空的。如果第一個和最後一個字符的內容不是{和},那麼錯誤是「無效的JSON。JSON內容中沒有識別出令牌。」 如果內容爲空{}或{},則誤差同上(屬性名稱「」是無效的。......「)

你能幫我嗎? 感謝

之間任何其他字符串

回答

0

我寧願利用StreamWriter class而不是Encoding class來避免任何編碼問題。

在您的例子來設置請求主體更換:

byte[] binary = Encoding.Unicode.GetBytes(content); 
httpWebRequest.ContentLength = binary.Length; 
using (System.IO.Stream requestStream = httpWebRequest.GetRequestStream()) 
{ 
    requestStream.Write(binary, 0, binary.Length); 
} 

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
{ 
    streamWriter.Write(content); 
} 
+0

不幸的是,這是不行的,拋出一個延伸: 類型的未處理的異常「System.Net .ProtocolViolationException'發生在System.dll中 此異常是因爲此代碼未設置httpWebRequest.ContentLength屬性。 –

+0

它返回什麼樣的錯誤,它適用於我 –

+0

@LászlóH。發生此錯誤的原因是,在刪除行'httpWebRequest.ContentLength = 0;'後,請求體長顯式設置爲0,錯誤應該消失。 –

0

從Unicode改變編碼UTF8解決問題:

來自:

byte[] binary = Encoding.Unicode.GetBytes(content); 

到:

byte[] binary = Encoding.UTF8.GetBytes(content); 
相關問題