WCF 中的 EndpointNotFoundException + Windows 窗体中托管的 NamedPipes

本文关键字:NamedPipes 窗体 中的 EndpointNotFoundException Windows WCF | 更新日期: 2023-09-27 18:32:35

>我创建了一个简单的代码,以允许使用 WCF 和 NamedPipe 进行跨应用程序域通信。我正在Windows 8.1上测试代码,它导致了EndpointNotFoundException。

这是我的代码:

服务合同

[ServiceContract(Namespace = "http://PoC.AppDomainWCF")]
    public interface ICrossAppDomainSvc
    {
        [OperationContract]
        bool HasPermission(String User, String Permission);
    }

程序.cs (WinForms)

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Thread thread = new Thread(new ThreadStart(StartService));
            thread.Start();
            Application.Run(new Form1());
        }
        static void StartService()
        {
            using (ServiceHost host = new ServiceHost(typeof(CrossAppDomainSvc), new Uri[] {
                new Uri("http://localhost:12000/AppDomainWCF/"),
                new Uri("net.pipe://localhost/")
            }))
            {
                var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
                host.AddServiceEndpoint(typeof(ICrossAppDomainSvc), binding, "CrossAppDomainSvc");
                // Add a MEX endpoint
                //ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior();
                //metadataBehavior.HttpGetEnabled = true;
                //metadataBehavior.HttpGetUrl = new Uri("http://localhost:12001/AppDomainWCF");
                //host.Description.Behaviors.Add(metadataBehavior);
                host.Open();
            }
        }
    }

客户端代码

NetNamedPipeBinding binding = new NetNamedPipeBinding();
            ChannelFactory<ICrossAppDomainSvc> channelFactory = new ChannelFactory<ICrossAppDomainSvc>(binding);
            EndpointAddress endpointAddress = new EndpointAddress("net.pipe://localhost/CrossAppDomainSvc");
            ICrossAppDomainSvc service = channelFactory.CreateChannel(endpointAddress);
            MessageBox.Show(service.HasPermission("Juliano", "XPTO").ToString());

在服务中引发异常。有权限调用。

我的代码有什么问题?

更新

由于问题已经得到解答并且我的概念验证正在发挥作用,我在 GitHub 上创建了一个存储库,以帮助任何需要允许跨应用程序域通信的人。

跨应用域WCF示例代码

WCF 中的 EndpointNotFoundException + Windows 窗体中托管的 NamedPipes

您打开 ServiceHost 并立即关闭它。 serviceHost.Open() 方法不会阻塞。因此,您的端点不存在,因为连接时主机已关闭