来自wcf代理的操作契约列表



我可能需要搜索或调查更多。但我想先问问你们…我有几个WCF服务托管在Windows上,在客户端我有代理与所有这些服务契约。我的应用程序正在使用它们,并且工作得很好。现在我想知道,如果我提供服务端点/我所拥有的其他东西,是否有任何方法可以从每个契约中获得操作列表。

结束品脱

http://localhost:8080/myservice/Echo

[ServiceContract]
public interface IEcho
{
    string Message { [OperationContract]get; [OperationContract]set; }
    [OperationContract]
    string SendEcho();
}

我需要一个方法来获取服务契约内部的操作列表…在这种情况下列表操作= SendEcho();我怎么得到这个点?

我编写了如下示例代码,但是您需要在您希望获得方法列表的服务的同一程序集中创建Echo服务:

public System.Collections.Generic.List<string> SendEcho()
    {
        // Get the current executing assembly and return all exported types included in it:
        Type[] exportedTypes = System.Reflection.Assembly.GetExecutingAssembly().GetExportedTypes();
        // The list to store the method names
        System.Collections.Generic.List<string> methodsList = new System.Collections.Generic.List<string>();
        foreach (Type item in exportedTypes)
        {
            // Check the interfaces implemented in the current class:
            foreach (Type implementedInterfaces in item.GetInterfaces())
            {
                object[] customInterfaceAttributes = implementedInterfaces.GetCustomAttributes(false);
                if (customInterfaceAttributes.Length > 0)
                {
                    foreach (object customAttribute in customInterfaceAttributes)
                    {
                        // Extract the method names only if the current implemented interface is marked with "ServiceContract"
                        if (customAttribute.GetType() == typeof(System.ServiceModel.ServiceContractAttribute))
                        {
                            System.Reflection.MemberInfo[] mi = implementedInterfaces.GetMembers();
                            foreach (System.Reflection.MemberInfo member in mi)
                            {
                                if (System.Reflection.MemberTypes.Method == member.MemberType)
                                {
                                    // If you want to have an idea about the method parameters you can get it from here: (count, type etc...)
                                    System.Reflection.ParameterInfo[] pi = ((System.Reflection.MethodInfo)member).GetParameters();
                                    // Check the method attributes and make sure that it is marked as "OperationContract":
                                    object[] methodAttributes = member.GetCustomAttributes(false);
                                    if (methodAttributes.Length > 0 && methodAttributes.Any(p => p.GetType() == typeof(System.ServiceModel.OperationContractAttribute)))
                                        methodsList.Add(member.Name);
                                }
                            }
                        }
                    }
                }
            }
        }
        return methodsList;
    }

希望这对你有帮助!

假设客户端引用了接口/服务契约?如果是,则不需要探测服务。只需使用反射来遍历接口的方法,检查哪些方法被[OperationContract]属性标记。

最新更新