2010-10-27 75 views
2

我使用ajax調用更新SharePoint列表的web服務。更新Sharepoint列表項時,從Web服務調用時出錯

它的工作原理,當我從單元測試調用的代碼,但運行在瀏覽器中的代碼會導致一個例外:

System.InvalidOperationException:操作無效由於對象的當前狀態。 在Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext的上下文) 在Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext的上下文) 在Microsoft.SharePoint.SPContext.get_Current() 在Microsoft.SharePoint.SPListItem.AddOrUpdateItem在Microsoft.SharePoint.SPListItem(布爾BADD,布爾bSystem,布爾bPreserveItemVersion,布爾bNoVersion,布爾bMigration,布爾bPublish,布爾bCheckOut,布爾bCheckin,的Guid newGuidOnAdd,的Int32 & ULID,對象& objAttachmentNames,對象& objAttachmentContents,布爾suppressAfterEvents) .UpdateInternal(Boolean bSystem,Boolean bPreserveItemVersion,Guid newGuidOnAdd,Boolean bMigration,Boolean bPublish,Boolean bNoVersion,Boolean bCheckOut,Bo奧利安bCheckin,布爾suppressAfterEvents) 在Microsoft.SharePoint.SPListItem.Update()

我的代碼更新列表項是:

SPSecurity.RunWithElevatedPrivileges(delegate() 
     { 
      using (SPSite site = new SPSite(siteURL)) 
      { 
       using (SPWeb web = site.OpenWeb(path)) 
       { 
        SPList userProfile = web.Lists[userList]; 
        SPQuery qry = new SPQuery 
        { 
         Query = 
          "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + 
          accountName + 
          "</Value></Eq></Where><ViewFields><FieldRef Name='ID' /><FieldRef Name='Title' /><FieldRef Name='LastUpdated' /><FieldRef Name='Reason' /></ViewFields>" 
        }; 

        SPListItemCollection spListItemCollection = userProfile.GetItems(qry); 

        if (spListItemCollection.Count == 1) 
        { 
         //edit user 
         SPListItem item = spListItemCollection[0]; 
         item["Updated"] = DateTime.Now; 
         item["Reason"] = updateReason; 
         item.Update(); 
        } 
       } 
      } 
     }); 
上item.Update

它錯誤();

+0

當您運行單元測試時,它是否在與Web服務相同的帳戶憑據下執行?我想知道這是否是一個安全問題。 – CBono 2010-10-27 12:48:00

+0

它對兩者使用相同的憑據。 – 2010-10-27 14:48:11

回答

0

的問題是安全。下面的行需要被添加(儘管不是理想的)

web.AllowUnsafeUpdates = true; 

我還除去線

SPSecurity.RunWithElevatedPrivileges(delegate() 

和改變了的SPSite和的SPWeb「使用」爲不使用。

+2

兩件事:首先,最好設置AllowUnsafeUpdates第二,SPSite和SPWeb上的使用不應該引起任何錯誤,如果你不使用using,那麼一定要在SPSite和SPWeb上顯式調用Dispose,否則你的應用程序會泄漏內存。http://msdn.microsoft.com/en-us/library/aa973248(office.12).aspx – 2010-10-28 12:29:08

1

嘗試增加this

HttpContext context = HttpContext.Current; 
if (HttpContext.Current != null) 
{ 
    if (context.Items["HttpHandlerSPWeb"] == null) 
     context.Items["HttpHandlerSPWeb"] = site.RootWeb; 
    if (context.Items["Microsoft.Office.ServerContext"] == null) 
     context.Items["Microsoft.Office.ServerContext"] = ServerContext.GetContext(site); 
} 
+0

您的回答很有幫助,它向我展示了與之前使用SPSecurity.RunWithElevatedPrivileges(delegate() ,因此我知道我必須刪除此行相同的SPSecurityException錯誤 – 2010-10-28 12:02:04

相關問題