【发布时间】:2014-04-11 06:40:51
【问题描述】:
“RunWithElevatedPrivileges”:在 C# 中以编程方式允许用户管理列表权限以将文件上传到共享点列表项对我没有帮助。我的代码是:
SPSecurity.RunWithElevatedPrivileges(delegate
{
SPWeb web = SPContext.Current.Site;
// my logic to upload file and edit list item attachments.
});
完整代码
protected void btn_Upload_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"C:\Upload.txt", true);
try
{
if (this.FileUpload1.HasFile)
{
string siteURL = SPContext.Current.Web.Url.ToString();
if (Request["Items"] != null && Request["ListId"] != null)
{
string SelectedItems = Convert.ToString(Request["Items"]);
string[] lstJobsIds = SelectedItems.Split(new string[] { "|" }, StringSplitOptions.None);
SPList list = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//SPSite site = SPContext.Current.Site;
using (SPSite site = new SPSite("http://sitrURL"))
{
using (SPWeb web = site.OpenWeb())
{
// Fetch the List
//list = web.Lists["ListName"];
sw.WriteLine("WEb is :" + web);
list = web.Lists["ListName"];
if (lstJobsIds.Length > 0)
{
////site.AllowUnsafeUpdates = true;
////web.AllowUnsafeUpdates = true;
for (int i = 0; i < lstJobsIds.Length; i++)
{
// Get the List item
if (lstJobsIds[i] != null && lstJobsIds[i] != string.Empty)
{
sw.WriteLine(lstJobsIds[i]);
SPListItem listItem = list.GetItemById(int.Parse(lstJobsIds[i]));
// Get the Attachment collection
SPAttachmentCollection attachmentCollection = listItem.Attachments;
Stream attachmentStream;
Byte[] attachmentContent;
sw.WriteLine(this.FileUpload1.PostedFile);
sw.WriteLine(this.FileUpload1.FileName);
attachmentStream = this.FileUpload1.PostedFile.InputStream;
attachmentContent = new Byte[attachmentStream.Length];
attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);
attachmentStream.Close();
attachmentStream.Dispose();
// Add the file to the attachment collection
attachmentCollection.Add(this.FileUpload1.FileName, attachmentContent);
// Update th list item
listItem.Update();
web.AllowUnsafeUpdates = true;
}
}
//web.AllowUnsafeUpdates = false;
//site.AllowUnsafeUpdates = false;
}
sw.Close();
}
}
});
}
}
}
catch (Exception ex)
{
sw.WriteLine(ex);
sw.Close();
}
}
现在当用户点击按钮上传文件时,他会得到HTTP Error 403 Forbidden。
那么,如何让有限制权限的用户正常执行我的自定义函数呢?
【问题讨论】:
-
你在哪里运行来自.timer 服务、事件处理程序、自定义页面的代码?
-
您必须在 RunWithElevatedPrivileges 中创建 SPWeb 对象。 SPContext - 它是用户的上下文,它具有有限的权限。顺便说一句,最佳做法是使用系统帐户设置而不是 RunWithElevatedPrivileges 创建 SPSite 对象。
-
@Mandar Jogalekar 我更新后的代码是在我的 Visual Studio 项目的应用页面中单击按钮,请帮助。
-
@Nikolay Zainchkovskiy 你说的怎么办?
标签: c# asp.net sharepoint iis-7 code-access-security