4

In C# / .NET 4.0 I am trying to retrieve a field value through reflection with:

var bar = foo.GetType()
  .GetField("_myField", BindingFlags.Instance | BindingFlags.NonPublic)
  .GetValue(foo)

I am a bit puzzled by the situation. The value returned is null, and yet, the field (when observed through the debugger) is not null. Even more puzzling, the code here above works for the other object properties.

The only odd aspect are the two flags IsSecurityCritical and IsSecuritySafeCritical that are true, but I am not even sure it's actually relevant to the situation.

I am ending up in such a situation with a small HttpModule.

public class MyModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += BeginRequest;
    }

    void BeginRequest(object sender, EventArgs e)
    {
         var app = (HttpApplication)sender;

         var rawContent = typeof(HttpRequest)
                .GetField("_rawContent", BindingFlags.Instance | BindingFlags.NonPublic)
                .GetValue(app.Request);

         // at this point 'rawContent' is null, while debugger indicates it is not.
    }
}

Any suggestion that would explain such a behavior?

Joannes Vermorel
  • 8,976
  • 12
  • 64
  • 104
  • The debugger sometimes hits code paths that you don't expect and don't see under normal conditions (like the ToString() methods, lazy loading stuff, etc...). The only way to check if your code is running well or not in these situations is to test w/o a debugget attached. That's Heisenberg uncertainty principle applied to .NET programming :-) – Simon Mourier Dec 14 '10 at 16:37
  • Is the field type a Nullable? (IE: int?, bool?, etc) – Tony Abrams Dec 14 '10 at 16:38

1 Answers1

5

This is caused by the security model in .net 4.0, as you're running an asp.net application, which is probably not running in full trust. As the field is security critical, you can't access it through reflection.

You can read a bit on the msdn about: Security Considerations for Reflection

Jb Evain
  • 17,319
  • 2
  • 67
  • 67