简体   繁体   中英

Finding asp.net webform methods through reflection

I am trying to find a method in a asp.net code behind class through reflection through the following code placed on the same page I querying.

MethodInfo MyMethod = this.GetType().GetMethod("Create", BindingFlags.Static);

But this always returns null , what is more strange is that at runtime the type of this is not MyAssembly.MyPage that type shows as ASP.MyPage_aspx . What is this type? and why am I not seeing the original code behind class type? and where do I find it?

Any idea how to solve this problem?

The ASP.NET compiler create a new class that inherits from your Page class. So it will have something like:

namespace ASP
{
    [CompilerGlobalScope]
    public class MyPage_aspx : MyPage, IHttpHandler
    {
        // all methods that resulted from parsing your ASPX page
        // Build controls, write literal text, etc
    }
}

The code that gets generated can be found in the Temporary ASP.NET Files files folder, either in your appdata folder of your user profile or in the .Net Framework folder, but it is also configurable where it will store these intermediate CS files and assemblies.

To find the static method (but it needs to be either public or protected) from your page add the following BindingFlag

BindingFlags.FlattenHierarchy 

based on the remarks found in the GetMethod doc:

Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

So your call will have at least to include that BindingFlag. Beyond that you also need the InvokeMethod ad Public flag to have that method returned. The complete call should look like:

var MyMethod = this.GetType().
      GetMethod(
          "Create", 
          BindingFlags.Static | 
          BindingFlags.FlattenHierarchy | 
          BindingFlags.InvokeMethod | 
          BindingFlags.Public);

This does assume your Create method is indeed static and not an private instance method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM