SharePoint C# Feature with http-Requests
-
06-02-2021 - |
题
I'm trying to make a http request from a C# feature for sharepoint. The request is made inside "ItemAdded" function of a List.
The request is made like this:
public override void ItemAdded(SPItemEventProperties properties) {
base.ItemAdded(properties);
EventFiringEnabled = false;
string currentSite = SPContext.Current.Web.Url;
using (SPSite spSite = new SPSite(currentSite)) {
using (SPWeb spWeb = spSite.OpenWeb()) {
SPSecurity.RunWithElevatedPrivileges(delegate () {
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
SPList l = spWeb.Lists["d.3_List"];
SPListItem item = l.Items.Add();
item["Title"] = "Success";
item.Update();
} catch (Exception ex) {
SPList l = spWeb.Lists["d.3_List"];
SPListItem item = l.Items.Add();
item["Title"] = "Exception: " + ex;
item.Update();
}
});
}
}
EventFiringEnabled = true;
}
But it always fails with the following error:
Does anyone know how to fix that?
解决方案 2
I fixed it, the problem was that I ran the feature in a sandboxed solution.
其他提示
What you can do is create a delegate that runs with elevated privileges within your function. This should allow you to run it. Give this a try:
EDITED: Give this a shot.
public override void ItemAdded(SPItemEventProperties properties) {
base.ItemAdded(properties);
string currentSite = SPContext.Current.Web.Url;
EventFiringEnabled = false;
using (SPSite spSite = new SPSite(currentSite))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate () {
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
} catch (Exception ex) {
Console.WriteLine("Error: " + ex.StackTrace);
}
});
}
}
EventFiringEnabled = true;
}