.net - 使用 Net.TCP 时在客户端添加 Web 引用

标签 .net wcf binding reference tcp

我正在尝试在我的 WCF 服务中使用 Net.TCP,它是自托管的,当我尝试通过 Web 引用向我的客户端添加此服务引用时,我无法访问该服务的类和方法,可以任何有任何想法来实现这一目标...... 在这种情况下我如何添加 Web 引用。我的服务有一种返回 int 的方法 (GetNumber)。

网络服务:

public class WebService : IWebService
{
    public int GetNumber(int num)
    {
        return num + 1;
    }
}

服务契约(Contract)代码:

[ServiceContract]
public interface IWebService
{
    [OperationContract]
    int GetNumber(int num);
}

WCF服务代码:

        ServiceHost host = new ServiceHost(typeof(WebService));
        host.AddServiceEndpoint(typeof(IWebService), new NetTcpBinding(), new Uri("net.tcp://" + Dns.GetHostName() + ":1255/WebService"));
        NetTcpBinding binding = new NetTcpBinding();
        binding.TransferMode = TransferMode.Streamed;
        binding.ReceiveTimeout = TimeSpan.MaxValue;
        binding.MaxReceivedMessageSize = long.MaxValue;
        Console.WriteLine("{0}", Dns.GetHostName().ToString());
        Console.WriteLine("Opening Web Service...");
        host.Open();
        Console.WriteLine("Web Service is running on port {0}",1255);
        Console.WriteLine("Press <ENTER> to EXIT");
        Console.ReadLine();

这很好用。唯一的问题是如何在我的客户端应用程序中添加此服务的引用。我只想发送号码并收到答复。 谁能帮帮我?

最佳答案

问题是服务的元数据(您服务的描述)未导出,这就是 Visual Studio 无法创建代理类的原因。

link解释了如何通过更改 xml 配置文件或直接在代码中导出服务的元数据。

链接中提供的解决方案的编码版本仍然存在问题,我将在下面解释。

当执行给出的代码时,你会得到一个异常提示

The contract name 'IMetadataExchange' could not be found in the list of
contracts implemented by the service M6.Servico.GetCurve.GetCrvService.
Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost
directly to enable support for this contract.

为了解决这个问题,我只是改变了事情的完成顺序。首先创建行为,设置其属性并将其添加到宿主的行为中。之后添加端点,包括 mexBinding

ServiceHost host = new ServiceHost(
    typeof(MyService),
    new Uri("http://localhost:8080/MyService"),
    new Uri("net.tcp://localhost:9000/MyService"));

ServiceMetadataBehavior metadataBehavior =
    new ServiceMetadataBehavior();
metadataBehavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(metadataBehavior);

host.AddServiceEndpoint(
    typeof(IMyService),
    new WSHttpBinding(),
    "");
host.AddServiceEndpoint(
        typeof(IMyService),
    new NetTcpBinding(),
    "");
Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
host.AddServiceEndpoint(
    typeof(IMetadataExchange),
    mexBinding,
    "net.tcp://localhost:9000/MyService/mex");

关于.net - 使用 Net.TCP 时在客户端添加 Web 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1062555/

相关文章:

c++ - 绑定(bind)到底是什么意思?

c# - 尝试阅读 MS Office 文档

c# - 现有连接被远程主机强行关闭

c# - 通过 WCF 以某种方式获取枚举描述 "generically"

c# - WCF [DataContract] 设置/获取未执行

c# - 绑定(bind)到 "IsExpanded"不适用于 TreeView 中的根节点

linux - Debian 8.5下无法打开10241端口

c# - 为什么我的 C# Soap Extension 没有被调用?

asp.net - 如何在 VS 2010 中调试 .NET Web 服务初始化代码?

c# - usercontrol 中的所有控件都为 null