【问题标题】:Consume WCF service from client without WCF Service Library project/assembly reference在没有 WCF 服务库项目/程序集参考的情况下从客户端使用 WCF 服务
【发布时间】:2016-01-28 20:36:47
【问题描述】:

以下问题可能重复,但没有足够的信息来回答我的问题。

Is possible to access WCF Service without adding Service Reference?

我已经按照本指南在 Visual Studio 中使用 WCF 服务库项目设置了 TCP 服务。

https://msdn.microsoft.com/en-us/library/ff649818.aspx

如果您从客户端(Windows 窗体项目)添加对 WCF 服务库项目的引用,这将非常有用。并在项目程序集中添加 using 语句并使用此代码。

        TcpService.Service myService = new TcpService.Service();
        myService.GetData(123);

但是,我不想在中添加对 TcpService 程序集的引用 调用方法“GetData”的项目。首先 以上问题的答案。

所以我尝试使用此代码。我添加了对 System.ServiceModel 的引用(和 using 指令)来解决大部分错误。但现在它说“找不到类型或命名空间名称'ServiceContract'(您是否缺少 using 指令或程序集引用?)”。我是否需要在我的服务中修改 App.Config,或者在下面调用此代码的项目中添加任何其他代码(关于“ServiceContract”)?

        BasicHttpBinding binding = new BasicHttpBinding();
        EndpointAddress address = new EndpointAddress("net.tcp://localhost:8523/Service");
        ChannelFactory<ServiceContract> factory = new ChannelFactory<ServiceContract>(binding, address);
        ServiceContract channel = factory.CreateChannel();
        channel.GetData(123);

注意:我将默认Service1.cs和默认接口IService1.cs重命名为Service.cs和IService.cs。没有“1”作为后缀,根据说明。我还在我的代码中将 WcfServiceLibrary1 重命名为 TcpService。此外,在 .NET 4.5 中,我根本不需要这行代码来工作。这个 .Close() 出错了。

myService.Close();

我在 Visual Studio 中添加了一个服务引用,方法是右键单击项目 > 添加 > 服务引用。但我在那里得到一个错误。

第二个对话框出错:

URI 前缀无法识别。元数据包含一个引用 无法解决:'net.tcp://localhost:8523/Service'。不能 连接到 net.tcp://localhost:8523/Service。连接尝试 持续时间跨度为 00:00:01.0011001。 TCP 错误代码 10061:否 可以建立连接,因为目标机器主动拒绝 它是 127.0.0.1:8523。无法建立连接,因为目标 机器主动拒绝它 127.0.0.1:8523 如果服务已定义 在当前解决方案中,尝试构建解决方案并添加 再次引用服务。

【问题讨论】:

    标签: c# .net wcf servicecontract


    【解决方案1】:

    指南缺少一步。除了httpGetEnabled 属性之外,我还将httpsGetEnabled 设置为“false”,并且成功了!之后,我在添加服务引用时不再收到错误消息。然后我将“ServiceContract”更改为“MyClientProject.ServiceReference1.IService”以引用新的服务参考。

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    
    ...
    
        <behaviors>
          <serviceBehaviors>
            <behavior name="">
              <serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
              <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    
    </configuration>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 2012-04-20
      相关资源
      最近更新 更多