簡體   English   中英

如何在C#中使用反射來列出.asmx的方法

[英]how to use reflection in C# to list the methods of an .asmx

給定引用asmx的url,我將如何顯示其所有方法名稱? 如果assembly =“ http://.../something/something.asmx”並且我試圖顯示該服務的方法名稱,那么到目前為止我該怎么辦? 我似乎無法在我看過的數百個示例中找到解決方案

   public TestReflection(string assembly)
    {
        Assembly testAssembly = Assembly.LoadFrom(assembly);
        Type sType = testAssembly.GetType();

        MethodInfo[] methodInfos = typeof(Object).GetMethods();
        foreach (MethodInfo methodInfo in methodInfos)
        {
            Console.WriteLine(methodInfo.Name);
        }
    }
typeof(Object).GetMethods()

您要求類型object所有方法

您需要在要獲取其方法的類型上調用GetMethods()。

嘗試這個:

public TestReflection(string assembly)
{
    Assembly testAssembly = Assembly.LoadFrom(assembly);
    Type sType = testAssembly.GetType("NamespaceOfYourClass.NameOfYourClassHere", true, true);

    MethodInfo[] methodInfos = sType.GetMethods();
    foreach (MethodInfo methodInfo in methodInfos)
    {
        Console.WriteLine(methodInfo.Name);
    }
}

這個想法是,在您的原始代碼中,您嘗試使用typeof(Object)來獲取方法,該方法將檢索Object類型的方法,這不是您想要的。

您需要知道要嘗試獲取的方法屬於哪個類。如果不知道,請將testAssembly.GetType(...替換為testAssembly.GetTypes()並遍歷所有類型,然后獲取方法每一個人。

除了反射,您實際上可以查詢Web服務的WSDL以獲得方法列表。 它可以簡化您的問題。 如果您打算使用反射,則必須在程序集中找到類型,然后使用此處其他答案中所述的其他方法來獲取方法。

您需要在從System.Web.Services.WebService繼承的類上尋找用[WebMethod]屬性修飾的方法。

代碼看起來像這樣(未經測試):

public TestReflection(string assembly)
{
    Assembly testAssembly = Assembly.LoadFrom(assembly); // or .LoadFile() here
    foreach (Type type in testAssembly.GetTypes())
    {
        if (type.IsSubclassOf(typeof(System.Web.Services.WebService)))
        {
            foreach (MethodInfo methodInfo in type.GetMethods())
            {
                if (Attribute.GetCustomAttribute(methodInfo, typeof(System.Web.Services.WebMethodAttribute)) != null)
                {
                    Console.WriteLine(methodInfo.Name);
                }
            }
        }
    }
}

所以我想出了如何得到我想要的東西

[SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
internal static void LoadWebService(string webServiceAsmxUrl)
{
    ParseUrl(webServiceAsmxUrl);
    System.Net.WebClient client = new System.Net.WebClient();
    // Connect To the web service
    System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
    // Now read the WSDL file describing a service.
    ServiceDescription description = ServiceDescription.Read(stream);
    ///// LOAD THE DOM /////////
    // Initialize a service description importer.
    ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
    importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
    importer.AddServiceDescription(description, null, null);
    // Generate a proxy client.
    importer.Style = ServiceDescriptionImportStyle.Client;
    // Generate properties to represent primitive values.
    importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
    // Initialize a Code-DOM tree into which we will import the service.
    CodeNamespace nmspace = new CodeNamespace();
    CodeCompileUnit unit1 = new CodeCompileUnit();
    unit1.Namespaces.Add(nmspace);
    // Import the service into the Code-DOM tree. This creates proxy code that uses the service.
    ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
    if (warning == 0) // If zero then we are good to go
    {
        // Generate the proxy code
        CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
        // Compile the assembly proxy with the appropriate references
        string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
        CompilerParameters parms = new CompilerParameters(assemblyReferences);
        CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
        // Check For Errors
        if (results.Errors.Count > 0)
        {
            foreach (CompilerError oops in results.Errors)
            {
                System.Diagnostics.Debug.WriteLine("========Compiler error============");
                System.Diagnostics.Debug.WriteLine(oops.ErrorText);
            }
            Console.WriteLine("Compile Error Occured calling webservice. Check Debug ouput window.");
        }
        // Finally, add the web service method to our list of methods to test
        //--------------------------------------------------------------------------------------------
        object service = results.CompiledAssembly.CreateInstance(serviceName);
        Type types = service.GetType();
        List<MethodInfo> listMethods = types.GetMethods().ToList();
}
}

在瀏覽器中粘貼http://.../something/something.asmx ,它將為您提供所有方法及其參數的列表?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM