Question

I am trying to make sure my ASP.Net library will work under Medium Trust. I'm having problems however in that I need to disable a bit of code if it is being run under medium trust.

How do I determine from C# if the current application is medium trust?

Specifically, I'm trying to read the customErrors section from web.config and I'm getting security errors

Was it helpful?

Solution

This article here describes a mechanism to determine the trust level:

Finding out the current trust level in ASP.NET

Here is the code just in case the link dies:

AspNetHostingPermissionLevel GetCurrentTrustLevel() {
  foreach (AspNetHostingPermissionLevel trustLevel in
      new AspNetHostingPermissionLevel [] {
        AspNetHostingPermissionLevel.Unrestricted,
        AspNetHostingPermissionLevel.High,
        AspNetHostingPermissionLevel.Medium,
        AspNetHostingPermissionLevel.Low,
        AspNetHostingPermissionLevel.Minimal 
      } ) {
    try {
      new AspNetHostingPermission(trustLevel).Demand();
    }
    catch (System.Security.SecurityException ) {
      continue;
    }

    return trustLevel;
   }

   return AspNetHostingPermissionLevel.None;
}

I just tested it in an ASP.NET MVC3 application running at Medium and then Full trust and it does what it says on the tin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top