我可能需要搜索或调查更多内容。但想到先问你们.. 我有几个WCF服务托管在Windows和客户端我有代理与所有这些服务合同。我的应用程序正在消耗它们,而且工作正常。现在我想知道,如果我给出服务端点/我拥有的其他内容,是否有任何方法可以从每个合同中获取操作列表。
结束品脱
http://localhost:8080/myservice/Echo
代理
[ServiceContract]
public interface IEcho
{
string Message { [OperationContract]get; [OperationContract]set; }
[OperationContract]
string SendEcho();
}
我需要一个方法来获取服务合同中的操作列表......在这种情况下 List opeartions = SendEcho(); 我该如何理解这一点?
答案 0 :(得分:1)
我编写了一个示例代码,如下所示,但您需要在与您希望获取方法列表的服务相同的程序集中创建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;
}
希望这有帮助!
答案 1 :(得分:0)
据推测,客户端正在引用接口/服务合同?如果是这样,则无需探测服务。只需使用反射来迭代界面的方法,检查哪些标记有[OperationContract]属性。