【问题标题】:get all service contract method names获取所有服务合同方法名称
【发布时间】:2016-06-08 11:56:24
【问题描述】:

我正在使用 WPF 中的 WCF 服务,我想列出服务中的所有方法名称。

我尝试了两种解决方案, 1.

MethodInfo[] methods = typeof(TypeOfTheService).GetMethods();
foreach (var method in methods)
{
    string methodName = method.Name;
}

它列出了所有函数,但还包括一些其他函数,例如“to string”、“open”、“abort”等。


2.

MethodInfo[] methods = typeof(ITimeService).GetMethods();

            foreach (var method in methods)
            {
                if (((System.Attribute)(method.GetCustomAttributes(true)[0])).TypeId.ToString() == "System.ServiceModel.OperationContractAttribute")
                {                 
                    string methodName = method.Name;
                }
            }

最终会出现错误,显示“索引超出范围”。

【问题讨论】:

  • 你确定每个方法都有一个属性吗?
  • 我会为此查询 WCF 框架元数据。它必须知道存在哪些确切的方法。
  • 不,所有方法都没有该属性...这是它的显示数组,我想克服它。

标签: c# wpf wcf


【解决方案1】:

您可以在服务合约中搜索方法,即接口,它不会包含任何方法如ToString():

var contractMethods = typeof(ITimeService).GetMethods(); // not TimeService

【讨论】:

    【解决方案2】:

    第二种方法的问题在于,并非所有方法似乎都具有OperationContract 属性。因此对于这些方法,GetCustomAttributes 返回一个空数组。现在,当您尝试访问数组的第一个元素时,您会收到此异常。

    你可以简单地做这样的事情:

    var attribute = method.GetCustomAttribute(typeof (OperationContractAttribute));
    
    if(attribute != null)
    {
        //...
    }
    

    查看该方法是否具有OperationContract 属性。

    如果你得到的是服务本身的类型,你可以得到它实现的所有接口,得到它们所有的方法,然后检查这些方法是否有OperationContract属性,如下所示:

    var methods =
        typeof (TimeService).GetInterfaces()
        .SelectMany(x => x.GetMethods())
        .ToList();
    
    foreach (var method in methods)
    {
        var attribute = method.GetCustomAttribute(typeof(OperationContractAttribute));
    
        if (attribute != null)
        {
            //...
        }
    }
    

    【讨论】:

    • 这个函数“method.GetCustomAttribute(typeof (OperationContractAttribute));”总是返回 null。
    • 你在ITimeService上测试吗?或TypeOfTheService?
    • 使用 TypeOfTheService。
    • 在您的问题中,在第二种方法中,您使用的是ITimeService。试试看,它会起作用的。还是需要从TypeOfTheService开始?
    • 哦,对不起,弄错了,我复制了我之前的代码,请看这个 MethodInfo[] methods = cs.GetType().GetMethods();字符串 [] 方法名=新字符串 [方法.长度]; names.ItemsSource = 字符串列表; foreach(方法中的 var 方法){ stringlist.Add(method.Name); }
    猜你喜欢
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2014-04-17
    • 2021-05-20
    相关资源
    最近更新 更多