【问题标题】:Hosting WCF Service in WPF Application在 WPF 应用程序中托管 WCF 服务
【发布时间】:2017-01-20 23:15:40
【问题描述】:

我正在尝试在 WPF 应用程序中托管 WCF 服务,但我无法这样做。

这是我实现的代码:

ServiceHost host = null;
using (host = new ServiceHost(typeof(WcfJsonTransferRestService.apiService)))
            {
                host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint1");
                host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint2");
                host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint3");

host.Open();

一切正常,运行良好,但服务没有启动。

有人知道我的问题可能是什么吗?

谢谢

【问题讨论】:

  • 您是否尝试过在调试器中单步执行代码?是否抛出任何错误?事件查看器中有什么东西吗?
  • 是的,一切正常,但是当我尝试连接(使用高级 REST 客户端)时,我收到一个错误,好像服务没有运行
  • 从您发布的代码看来,您正在托管一个 SOAP 服务 - REST 与 SOAP 不同。您是否尝试过使用WebHttpBinding 而不是WSHttpBinding
  • 我之前实际上有 basicHttpBinding,我尝试了一些不同的东西,以及我最终使用 WSHttpBinding 的方式......但是你是对的,我应该使用 WebHttpBinding......不过还是不开心。
  • 我编辑了我的问题以包含 WebHttpBinding

标签: c# wpf wcf wcf-rest


【解决方案1】:

最可能的问题是您已将ServiceHost 的创建和打开封装在using 语句中。一旦 using 语句完成(从您发布的代码中并不清楚它在哪里执行),ServiceHost 实例将被关闭。

换句话说,如果你像这样在host.Open(); 之后关闭using 块:

using (host = new ServiceHost(typeof(WcfJsonTransferRestService.apiService)))
{
    host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint1");
    host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint2");
    host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint3");

    host.Open();
}

主机将关闭,您的应用程序将无法接收请求。通常,您会希望在应用程序启动时(或者可能在给定事件上)打开主机,然后在应用程序退出时将其关闭。

【讨论】:

  • 谢谢蒂姆!我不知道我是怎么错过的!
  • 我认为有几个示例有使用 in,它会被复制到人民代码中。
猜你喜欢
  • 2012-03-16
  • 2011-10-05
  • 2012-11-29
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多