使用RunWithElevatedPrivileges时如何更改"Modified By"?

Ale*_*gas 13 security sharepoint

我们有一个Web部件,可以将文档上载到文档库.上载文档的用户可能无法访问目标位置,因此添加文件的代码在RunWithElevatedPrivileges块中执行.这意味着"修改者"字段始终设置为"系统帐户".这是代码:

SPSecurity.RunWithElevatedPrivileges(
    delegate
    {
        using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.Url))
        using (SPWeb targetWeb = elevatedSite.OpenWeb(webUrl))
        {
            targetWeb.AllowUnsafeUpdates = true;
            SPFile newFile = files.Add(filename, file);
            SPListItem item = newFile.Item;

            // TODO: Insert code to set Modified By

            item.SystemUpdate();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

需要将"Modified By"字段设置为当前用户的名称(在上面的TODO行中),但以下尝试均未起作用:

item["Modified By"] = SPContext.Current.Web.CurrentUser;

item["Author"] = SPContext.Current.Web.CurrentUser;

item["Modified By"] = new SPFieldUserValue(
SPContext.Current.Web, SPContext.Current.Web.CurrentUser.ID,
SPContext.Current.Web.CurrentUser.Name);

item["Author"] = new SPFieldUserValue(
SPContext.Current.Web, SPContext.Current.Web.CurrentUser.ID,
SPContext.Current.Web.CurrentUser.Name);
Run Code Online (Sandbox Code Playgroud)

有没有人知道允许更改"修改者"值的解决方案?

Ale*_*gas 10

我做了一些测试......

item["Editor"] = SPContext.Current.Web.CurrentUser;
item["Author"] = SPContext.Current.Web.CurrentUser;
item.SystemUpdate();
Run Code Online (Sandbox Code Playgroud)

"创建者"设置为当前用户,但"修改者"设置为"系统帐户".

item["Editor"] = SPContext.Current.Web.CurrentUser;
item["Author"] = SPContext.Current.Web.CurrentUser;
item.Update();
Run Code Online (Sandbox Code Playgroud)

"创建者"和"修改者身份"都设置为当前用户.

问题是使用SPListItem.SystemUpdate(),它与API文档所声明的完全相反,至少在使用提升的权限运行时.

注意: SPContext.Current.Web.CurrentUser在SPSecurity.RunWithElevatedPrivileges中运行时确实选择当前用户而不是系统帐户.(是否应该像这样使用是另一个问题.)


Hen*_*chi 6

解决此问题的一种方法是提升权限之前将当前登录的用户存储在内存中.稍后在更新请求中,将"系统帐户"替换为您的变量.

见下文:

// Keep a reference of the Logged in user in memory
SPUser currentUser = SPContext.Current.Web.CurrentUser;

SPSecurity.RunWithElevatedPrivileges(
delegate
{
    using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.Url))
    using (SPWeb targetWeb = elevatedSite.OpenWeb(webUrl))
    {
        targetWeb.AllowUnsafeUpdates = true;
        SPFile newFile = files.Add(filename, file);
        SPListItem item = newFile.Item;

        // Replace 'System Account' with current user
        item["Author"] = currentUser;
        item["Modified By"] = currentUser;

        item.SystemUpdate();
    }
});
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.