FieldInfo.GetValue return null for a private member while debugger indicates field is non null?
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 Begi开发者_StackOverflownRequest(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?
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
精彩评论