如何从 C# 中的 WCF Rest 服务获取方法名称的所有 URL 板



我有一个休息服务网址,如下所示http://XXXXXXXX/RestServices/Project.svc

此 SVC 有两种方法,

[OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "UserLogin")]
    ResultInfo Login(Login objLogin);
[OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SaveUser")]
    ResultInfo User(User objUser);

方法名称是"登录名"和"用户",但"UriTemplate 名称"相应地是"用户名"和"保存用户"。

我想获取 C# 中的输出列表,如下所示

UserLogin
SaveUser

需要您的帮助。

可以使用以下方法获取方法名称

在 ASPX 页中:

<asp:ListBox ID="lstMethodName" runat="server" Visible="true" AutoPostBack="true"
        Style="height: 150px; width:300px; overflow: auto;"></asp:ListBox>

在代码隐藏中:

string wsdlUrl = "http://XXXXXXXX/RestServices/Project.svc?wsdl"; // WCF wsdl address
                XmlTextReader myReader = new XmlTextReader(wsdlUrl);
                if (ServiceDescription.CanRead(myReader))
                {
                    ServiceDescription myDescription = ServiceDescription.Read(myReader);
                    foreach (PortType pt in myDescription.PortTypes)
                    {
                        foreach (Operation op in pt.Operations)
                        {
                            lstMethodName.Items.Add(op.Name);
                        }
                    }
                }

添加命名空间:

 using System.Web.Services.Description;
 using System.Collections.Generic;

最新更新