【问题标题】:Get ServiceContract Methods from WCF从 WCF 获取 ServiceContract 方法
【发布时间】:2013-01-30 09:34:30
【问题描述】:

我想列出具有“OperationContractAttribute”属性的 WCF 服务中的所有方法

为此,我使用以下代码:

var service = assembly.GetType(typeName);
        if (service == null)
            return webMethodsInfo;
        var methodsInfo = service.GetMethods();
        webMethods = methodsInfo.Where(method => method.GetCustomAttributes
             (typeof(OperationContractAttribute), true).Any()).ToList();

因此,OperationContractAttribute 是在接口 (IClassA) 中指定的,当我尝试在 ClassA 类中搜索此方法属性时,它找不到它,但是我为方法 GetCustomAttributes 指定了标志 true 以搜索祖先

【问题讨论】:

  • 希望这可以帮助您链接到类似的 Q/A stackoverflow.com/questions/2720617/…
  • 不,因为我只需要 OperationContract 方法而不是所有方法(链接中的解决方案列出了所有方法(包括 ToString、GetHashCode 等...))

标签: wcf operationcontract


【解决方案1】:

这样就可以了

 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;
                }
            }

【讨论】:

  • 如果一个方法有多个属性或者根本没有属性怎么办?
  • 它应该在 if 中处理:if(method.GetCustomAttributes(true).Any(attrib => ((System.Attribute)attrib).TypeId.ToString() == "System.ServiceModel .OperationContractAttribute"))
【解决方案2】:
webMethods = service.GetInterface(serviceContract).GetMethods().Where(
    method => method.GetCustomAttributes
      (typeof(OperationContractAttribute)).Any())
      .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多