使用以下代码块时,listItem.Update会失败,并显示NullReferenceException:
SPWeb web = null;
SPList list = null;
SPListItem listItem = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(this.SiteUrl))
{
web = site.OpenWeb();
list = web.Lists[this.ListName];
listItem = list.Items.Add();
listItem["Background"] = "foo";
}
}
);
listItem.Update();
}
catch
{
}
finally
{
web.Dispose();
}如果我在匿名委托中移动listItem.Update()方法,我会得到“由于对象的当前状态,操作无效”。
是的,我已经对其进行了梳理,并尝试了许多排列,但都没有成功。
有什么想法吗?
更新:在第一个注释之后,我尝试从代码中删除匿名委托,看看它是否运行得更好:
// store the selected item to pass between methods
public T SelectedItem { get; set; }
// set the selected item and call the delegate method
public virtual void Save(T item)
{
SelectedItem = item;
try
{
SPSecurity.RunWithElevatedPrivileges(SaveSelectedItem);
}
catch
{
}
}
public virtual void SaveSelectedItem()
{
if (SelectedItem != null)
{
using (SPSite site = new SPSite(this.SiteUrl))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[this.ListName];
SPListItem listItem = list.Items.Add();
//UpdateListItem(listItem, SelectedItem);
listItem["Background"] = "foo";
listItem.Update();
}
}
}
}并且此操作仍然失败“操作由于对象的当前状态而无效”。在这两个代码示例中,site.Impersonating看起来都是假的。我使用的是Windows Auth和web.config中的模拟。这是从ASP.Net开发服务器运行的。
发布于 2010-01-16 04:40:44
我在这个网站上找到了一个例子(黑忍者软件)。我创建了一个对该站点的引用,获取其SystemAccount令牌,然后使用admin令牌创建另一个对该站点的引用。一开始对我来说似乎有点老生常谈--但是,嘿--我有一个截止日期。
最终的工作方法主体现在看起来像:
SPListItem new_item = null;
SPSite initialSite = new SPSite(this.SiteUrl);
using (var site = new SPSite(this.SiteUrl, initialSite.SystemAccount.UserToken))
{
// This code runs under the security context of the SHAREPOINT\system
// for all objects accessed through the "site" reference. Note that it's a
// different reference than SPContext.Current.Site.
using (var elevatedWeb = site.OpenWeb())
{
elevatedWeb.AllowUnsafeUpdates = true;
SPList list = elevatedWeb.Lists[this.ListName];
new_item = list.Items.Add();
UpdateListItem(new_item, item);
if (new_item != null)
{
new_item.Update();
}
}
}
initialSite.Dispose();https://stackoverflow.com/questions/2066078
复制相似问题