[C#] 取得.net WebService(.asmx) 的函式(Method)名稱

2013-06-11

上篇文章提到了 取得.net WebService(.asmx) 的自訂複雜型別

這篇文章,我們來取得,關於Web Service 中所有的 Method 名稱.

2013-06-11_121942

看一下 WSDL

2013-06-11_122259

其實都藏在 wsdl:operation 的 name  的屬性中..

所以我們依然透過 ServiceDescription 來取得..

/// <summary>
/// 透過網址取得資料後 並且讀為 GeServiceDescriptionFromServicePath
/// </summary>
/// <param name="servicePath"></param>
/// <returns></returns>
private ServiceDescription GeServiceDescriptionFromServicePath(string servicePath)
{
    if (!servicePath.ToLower().Contains("?wsdl"))
    {
        servicePath = servicePath + "?wsdl";
    }
 
    var wc = new WebClient();
    wc.Encoding = UTF8Encoding.UTF8;
    byte[] byteArray = Encoding.UTF8.GetBytes(wc.DownloadString(servicePath));
    var stream = new MemoryStream(byteArray);
    return ServiceDescription.Read(stream);
}
 
 
protected void btnGetMethods_Click(object sender, EventArgs e)
{
    var serviceDesc = GeServiceDescriptionFromServicePath(txtWebServicePath.Text);
 
    //取得所有Method Name .
    var allMethodNames = GetAllMethodsName(serviceDesc);
 
    ltlResult.Text = "";
    ltlResult.Text += "<ul>";
    foreach (var s in allMethodNames)
    {
        ltlResult.Text += "<li>" + s + "</li>";
    }
    ltlResult.Text += "</ul>";
}
 
 
 
/// <summary>
/// 取得所有 ServiceDescription 中 Methods 的名稱
/// </summary>
/// <param name="serviceDescription"></param>
/// <returns></returns>
private string[] GetAllMethodsName(ServiceDescription serviceDescription)
{
    var res = new List<string>();
 
    foreach (PortType portType in serviceDescription.PortTypes)
    {
        res.AddRange(from Operation operation in portType.Operations select operation.Name);
    }
 
    return res.ToArray();
}

 


結果:


2013-06-11_122519


中間都抽離的很簡單易懂..需要用到就自行改寫瞜.


Code:


當麻許的超技八 2014 | Donma Hsu Design.