FieldInfo.GetValue return null for a private member while debugger indicates field is non null?

StackOverflow https://stackoverflow.com/questions/4441561

  •  10-10-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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

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