【问题标题】:Consume WCF service in winform, how to dynamically set Endpoint element and contractwinform中消费WCF服务,如何动态设置Endpoint element和contract
【发布时间】:2015-07-30 10:58:09
【问题描述】:

我已经构建了一个测试 WCF 服务 Service1.svc 我已将服务的服务引用添加到我的 Winform。它运行良好,我可以轻松地在 winform 中使用 WCF 服务。但是我遇到了一个大问题:

  1. 当我重命名或删除“MyProject.exe.config”文件时。它显示错误“找不到名称为 BasicHttpBinding_IService1 和合同 ServiceReferenct1.IService1 的端点元素

    由于“MyProject.exe.config”文件包含我不想与客户或任何人共享的绑定和端点地址.

    有没有办法在不使用“MyProject.exe.config”文件的情况下动态设置端点元素和合同?

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" />
            </basicHttpBinding>
        </bindings>

        <client>
            <endpoint  address="http://svc.phed.net/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
                name="BasicHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>
  1. 如何更改服务显示的默认消息:

    您已创建服务。 要测试此服务,您需要创建一个客户端并使用它来调用该服务。您可以使用命令行中的 svcutil.exe 工具执行此操作,语法如下:

【问题讨论】:

    标签: .net winforms web-services wcf


    【解决方案1】:

    如果没有服务配置,可以手动创建代理。

    这是一个例子:

    var binding = new BasicHttpBinding();
                    var endpoint = new EndpointAddress("YourEndPoint");
                    var channelFactory = new ChannelFactory<YourInterface>(binding, endpoint);
    
                    YourInterface client = null;
                    client = channelFactory.CreateChannel();
                    client.YourOperation();
    

    在上面的例子中,我使用了 BasicHttpBinding。如果您使用其他绑定,只需使用正确的类,例如 NetTcpBinding。

    如果您在 try/catch 块中处理您的服务,您可以处理此错误并向您的客户抛出最友好的消息。

    希望对你有帮助。

    【讨论】:

    • 我正在使用以下方法创建服务对象:Dim endpoint = New EndpointAddress("svc.phed.net/Service1.svc") Dim SvcObj As New ServiceReference1.Service1Client("BasicHttpBinding_IService1", endpoint) SvcObj.GetData(1021) SvcObj.Close()
    • 有什么办法可以关闭它,比如 SvrObj.Close()
    • 是的,您可以关闭 ChannelFactory。在我上面发布的示例中,您可以使用 channelFactory.Close(); 关闭它
    • 从网络浏览器访问服务svc.phed.net/Service1.svc 时,它会显示一条默认消息,如我在我的问题中所示。有什么办法可以更改该消息?
    • 是的,你可以,你必须在你的 Web.config 中包含这个标签: 这个标签必须在 在此处阅读更多信息:social.msdn.microsoft.com/Forums/vstudio/en-US/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    相关资源
    最近更新 更多