我正在使用ajax来调用更新共享点列表的Web服务。
当我从单元测试中调用代码时,它可以工作,但在浏览器中运行代码会导致异常:
System.InvalidOperationException:由于对象的当前状态,操作无效。 在Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context) 在Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context) 在Microsoft.SharePoint.SPContext.get_Current() at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd,Boolean bSystem,Boolean bPreserveItemVersion,Boolean bNoVersion,Boolean bMigration,Boolean bPublish,Boolean bCheckOut,Boolean bCheckin,Guid newGuidOnAdd,Int32& ulID,Object& objAttachmentNames,Object& objAttachmentContents,Boolean suppressAfterEvents ) at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem,Boolean bPreserveItemVersion,Guid newGuidOnAdd,Boolean bMigration,Boolean bPublish,Boolean bNoVersion,Boolean bCheckOut,Boolean bCheckin,Boolean 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 :(得分: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);
}
答案 1 :(得分:0)
问题在于安全性。需要添加以下行(虽然不理想)
web.AllowUnsafeUpdates = true;
我也删除了这行
SPSecurity.RunWithElevatedPrivileges(delegate()
并将SPSite和SPWeb更改为不使用“使用”。