「RunWithElevatedPrivileges」:以編程方式在C#中,它不幫助我允許用戶沒有管理列表權限將文件上傳到共享點列表項目。我的代碼是:「RunWithElevatedPrivileges」共享點
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
。
那麼,如何讓用戶有限制權限來正常執行我的自定義函數呢?
你在哪裏運行的代碼from.timer服務,事件處理程序,自定義頁面? –
您必須在RunWithElevatedPrivileges內創建SPWeb對象。 SPContext - 它是用戶的上下文,它具有有限的權限。順便說一句,最好的做法是創建SPSite對象與系統帳戶設置,而不是RunWithElevatedPrivileges。 –
@ Mandar Jogalekar我的更新發布的代碼是在我的Visual Studio項目的應用程序頁面中點擊按鈕,請大家幫忙。 – user3203960