If you would like to discuss anything, please contact me via email: Howard.Bayliss@sequence.co.uk

Thursday, February 10, 2011

LoadControl() Request failed

I was tearing my hair out over an issue with using the UserControl.LoadControl method from within SharePoint, which kept throwing this exception:

Exception Details: System.Security.SecurityException: Request failed.

We run our code using the least priviledge possible, which means creating a custom CAS policy. However, no amount of tweaking the CAS policy seem to fix the issue.

It seems this is a common issue (see this blog post). People who have commented on that blog suggest a number of solutions. However, I found the only solution was to:
  1. Call the LoadControl method from an assembly located in the GAC.
  2. Use the PermissionSet Assert method to obtain sufficient privileges
Here is an example of the code:

public static Control LoadControl(UserControl parentControl, string controlName)
{
Control control = null;

System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
permissionSet.Assert();

try
{
string controlPath = String.Format("~/_controltemplates/{0}", controlName);
control = parentControl.LoadControl(controlPath);
}
finally
{
System.Security.CodeAccessPermission.RevertAssert();
}

return control;
}


No comments:

Post a Comment