c# - 如何使用反射调用 WCF 服务?

标签 c# wcf wcf-binding

我有WCF服务端点;我无权访问该服务的接口(interface)(即契约(Contract))。我有需要调用的 EndPoint 详细信息和 MethodName。

如何在 C# 中执行此操作;我正在使用 netTcpBinding...

提前致谢

海洋

最佳答案

不确定这是否正是您想要的,但您可以使用 WsdlImporter 联系 WSDL 并获取元数据(如 DataContracts 和 OperationContracts)。例如:

        MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;

        // Get Metadata file from service
        MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress, mexMode);
        mexClient.ResolveMetadataReferences = true;
        MetadataSet metaSet = mexClient.GetMetadata(mexAddress, mexMode);

        //Import all contracts and endpoints
        WsdlImporter importer = new WsdlImporter(metaSet);
        var contracts = importer.ImportAllContracts();
        ServiceEndpointCollection allEndpoints = importer.ImportAllEndpoints();

        //Generate type information for each contract
        ServiceContractGenerator generator = new ServiceContractGenerator();
        this.EndpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();

        foreach (ContractDescription contract in contracts)
        {
            generator.GenerateServiceContractType(contract);
            // Inspect if the name matches one you're looking for, or do whatever
            //  else you might need
        }

然后就可以动态地将代码编译到内存中:

// Generate a code file for the contracts 
        CodeGeneratorOptions options = new CodeGeneratorOptions();
        options.BracingStyle = "C";
        CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");

        // Compile the code file to an in-memory assembly
        // Don't forget to add all WCF-related assemblies as references
        CompilerParameters compilerParameters = new CompilerParameters(
            new string[] { 
                "System.dll", "System.ServiceModel.dll", 
                "System.Runtime.Serialization.dll" });
        compilerParameters.GenerateInMemory = true;

        CompilerResults results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, generator.TargetCompileUnit);

最后,您可以执行相应的方法:

Type clientProxyType = this.Cr.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(listServiceContracts.SelectedValue) != null && t.GetInterface(typeof(ICommunicationObject).Name) != null);
object dataContract = this.Cr.CompiledAssembly.CreateInstance(dataContractType.FullName, false, System.Reflection.BindingFlags.CreateInstance, null, null, CultureInfo.CurrentCulture, null);

// set the dataContract properties however they need to be set

// Get the first service endpoint for the contract
        ServiceEndpoint serviceEndPoint = this.EndpointsForContracts[listServiceContracts.SelectedValue].First();

        object clientProxyInstance = this.Cr.CompiledAssembly.CreateInstance(clientProxyType.Name, false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { serviceEndPoint.Binding, serviceEndPoint.Address }, CultureInfo.CurrentCulture, null);

        Type myType = clientProxyInstance.GetType();
        object[] arg = { dataContract };

        // Now call the remote procedure via SOAP, get back response
        var returnVal = myType.InvokeMember("OPERATION YOU WANT TO EXECUTE", BindingFlags.InvokeMethod, null, clientProxyInstance, arg);

同样,这可能不适合您想要做的事情,而且您的帖子已经很久以前了,所以这可能是旧新闻。但以防万一...希望这有帮助。您可能需要检查返回的类型以确定如何正确设置 DataContract 参数。另外,上面假设您调用的方法仅接受一个参数,即 DataContract 对象。

希望这能让您走上正轨(如果您仍然需要的话)。

关于c# - 如何使用反射调用 WCF 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11568831/

相关文章:

c# - wcf https ssl 中的服务端点出错。找不到与具有绑定(bind) WebHttpBinding 的端点的方案 http 匹配的基址

c# - 使用 NetTCPBinding 进行回调

vb.net - 通过 HTTPS 的 wsHTTPBinding 导致错误 400 'Bad Request'

c# - 从 List<Point> 中获取 3 个最常见的点

c# - 在 app.config 中使用 <rollForwardenabled ="true"/>

c# - 找不到配置绑定(bind)扩展 'system.serviceModel/bindings/basicHttpsBinding'

c# - WCF 双工 : Send callback to a specific subscribed ASP. NET Webforms 客户端

c# - 如何使用 Silverlight GET HttpWebRequest 设置 header ?

c# - FEATURE_PAL 编译器指令在 .net 4 源代码中的含义是什么

c# - 同步 WCF 操作的异步实现