user441521
user441521

Reputation: 6998

asp.net codebehind find webmethods

In the code behind for each page, how can I use reflection to get all the webmethods I have defined on that page?

Currently I have the following and call it in the Page_Load() but it doesn't find my 1 static function that I have a webmethod attribute on.

MethodInfo[] methods = this.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
    foreach (Attribute attribute in method.GetCustomAttributes(true))
    {
        if (attribute is WebMethodAttribute)
        {
        }
    }
}

Upvotes: 0

Views: 194

Answers (1)

Mate
Mate

Reputation: 5284

Try this for Public static :

 public partial class Default : System.Web.UI.Page
    {
        public Default()
        {

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            MethodInfo[] methodInfos = typeof(Default).GetMethods(BindingFlags.Public |
                                                      BindingFlags.Static);
            foreach (MethodInfo method in methodInfos)
            {
                foreach (Attribute attribute in method.GetCustomAttributes(true))
                {
                    if (attribute is WebMethodAttribute)
                    {
                    }
                }
            }

        }
        [WebMethod]
        public static void A() 
        { 
        }
    }

Works for me

Upvotes: 1

Related Questions