Windows Service中使用App.Config的WCF命名管道

时间:2019-03-27 00:22:53

标签: c# wcf app-config named-pipes

我很沮丧。好的,这是错误。

  

在net.pipe:// localhost / MyIpcAppToService上没有侦听终结点的端点可以接受该消息。这通常是由不正确的地址或SOAP操作引起的。有关更多详细信息,请参见InnerException(如果存在)。

我终于使App.Config文件正常运行,至少没有任何抱怨。

当前App.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
    </startup>
    <system.serviceModel>
        <services>
            <service behaviorConfiguration="MyServiceBehavior" name="MyService.Communication.IpcAppToService">
                <endpoint address="net.pipe://localhost/MyIpcAppToService" binding="wsDualHttpBinding" bindingConfiguration="MyAppToServiceEndpointBinding" contract="MyIpc.IIpcAppToService"/>
                <endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange"/>
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8733/MyService/"/>
                    </baseAddresses>
                </host>
            </service>
  </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="MyServiceBehavior">
                    <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment  to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                    <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add scheme="http" binding="wsHttpBinding" bindingConfiguration="MyAppToServiceEndpointBinding" />
        </protocolMapping>
        <bindings>
            <wsDualHttpBinding>
                <!-- https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/wshttpbinding -->
                <binding name="MyAppToServiceEndpointBinding"
                                 transactionFlow="true"
                                 sendTimeout="00:01:00"
                                 maxReceivedMessageSize="2147483647"
                                 messageEncoding="Mtom">
                </binding>
            </wsDualHttpBinding>
        </bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
            <baseAddressPrefixFilters>
                <add prefix="http://localhost:8733"/>
            </baseAddressPrefixFilters>
        </serviceHostingEnvironment>
    </system.serviceModel>
    <appSettings>
        <add key="countoffiles" value="7"/>
        <add key="logfilelocation" value="abc.txt"/>
    </appSettings>
</configuration>

我曾经有过:

<endpoint address="http://localhost:8733/MyIpcAppToService" ...

,并在Windows服务OnStart()事件中:

(此问题后,以下代码已注释掉,因为App.config文件应该启动named.pipe。)

public Boolean CreatePipeServer()
{
    string eventText = $"My Service: CommAppToService::CreatePipeServer(IPC App to Service){Environment.NewLine}";
    try
    {
        if (null != this.ServiceParent.HostIpcAppToService)
            this.ServiceParent.HostIpcAppToService = null;

        string pipeBaseAddress = @"net.pipe://localhost/MyIpcAppToService";
        this.ServiceParent.HostIpcAppToService = new ServiceHost(typeof(IpcAppToService), new Uri(pipeBaseAddress));
        NetNamedPipeBinding pipeBinding = new NetNamedPipeBinding()
        {
            //ReceiveTimeout = new TimeSpan(0, 0, 0, 0, Constants.My_TimeoutMsSendReceive),
            //SendTimeout = new TimeSpan(0, 0, 0, 0, Constants.My_TimeoutMsSendReceive),
        };
        this.ServiceParent.HostIpcAppToService.AddServiceEndpoint(typeof(IIpcAppToService), pipeBinding, "MyIpcAppToService");
        this.ServiceParent.HostIpcAppToService.UnknownMessageReceived += HostIpcAppServer_UnknownMessageReceived;
        this.ServiceParent.HostIpcAppToService.Faulted += HostIpcAppServer_Faulted;
        this.ServiceParent.HostIpcAppToService.Closing += HostIpcAppServer_Closing;
        this.ServiceParent.HostIpcAppToService.Closed += HostIpcAppServer_Closed;

        this.IpcAppToService = new IpcAppToService();
        this.IpcAppToService.ApplyDispatchBehavior(this.ServiceParent.HostIpcAppToService);
        this.IpcAppToService.Validate(this.ServiceParent.HostIpcAppToService);
        this.ServiceParent.HostIpcAppToService.Open();

        return true;
    }

我了解到该服务将自动启动放置在App.Config文件(实际上是MyExeName.exe.config文件)中的服务。我不断查看代码,发现它们几乎相同,因此我将http://替换为net.pipe://

可悲的是,旧代码,新代码,介于两者之间的代码,什么都没有。我一直收到同样的错误。

我使用以下内容从桌面应用程序连接到服务。

public static Boolean ConnectToService()
{
    try
    {
        var callback = new IpcCallbackAppToService();
        var context = new InstanceContext(callback);
        var pipeFactory = new DuplexChannelFactory<IIpcAppToService>(context, new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyIpcAppToService"));
        Program.HostIpcAppToService = pipeFactory.CreateChannel();
        Program.HostIpcAppToService.Connect();
        CommAppToService.IsPipeAppToService = true;

        return true;
    }

    catch (Exception ex)
    {
        // Log the exception.
        Errors.LogException(ex);
    }

    return false;
}

对于它的价值,这里是:

接口

[ServiceContract(SessionMode = SessionMode.Allowed, CallbackContract = typeof(IIpcCallbackAppToService))]
public interface IIpcAppToService
{
    [OperationContract(IsOneWay = false)]
    [FaultContractAttribute(typeof(IpcAppToServiceFault))]
    UInt16 GetServiceId();

    ...
}

服务:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class IpcAppToService : IIpcAppToService, IErrorHandler
{
    public static IIpcCallbackAppToService Callback { get; set; } = null;

    public void OpenCallback()
    {
        IpcAppToService.Callback = OperationContext.Current.GetCallbackChannel<IIpcCallbackAppToService>();
    }

    public void CloseCallback()
    {
        IpcAppToService.Callback = null;
    }

    public void SendMessage(string message)
    {
        //MessageBox.Show(message);
    }

    public UInt16 GetServiceId()
    {
        return Constants.My_Id_AppToService;
    }

    ...
}
我的桌面WinForms应用程序中的

内部异常 (请注意,没有比这更多的内部例外了。):

  

“在本地计算机上找不到管道端点'net.pipe:// localhost / MyIpcAppToService'。”

为什么我继续看到此错误?

在第一个答案后更新

我要采取的方向与答案相反,但还是一样,即服务以App.config开始,而client使用C#代码。

遗憾的是,我仍然遇到相同的错误。

修订的服务器端App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
    </startup>
    <system.serviceModel>
        <services>
            <service behaviorConfiguration="BehaviorMyService" name="MyService.Communication.IpcAppToService">
                <endpoint address="net.pipe://localhost/MyIpcAppToService"
                                    binding="netNamedPipeBinding"
                                    bindingConfiguration="EndpointBindingMyAppToService"
                                    contract="MyIpc.IIpcAppToService"
                                    />
                <endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange"/>
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8733/MyService/"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="BehaviorMyService">
                    <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
                    <serviceMetadata httpGetEnabled="true"
                                                     httpsGetEnabled="true"
                                                     />
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment  to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                    <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <bindings>
            <netNamedPipeBinding>
                <!-- https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/wshttpbinding -->
                <binding name="EndpointBindingMyAppToService"
                                 closeTimeout="00:01:00"  
                                 openTimeout="00:01:00"   
                                 receiveTimeout="00:10:00"   
                                 sendTimeout="00:01:00"  
                                 transactionFlow="false"   
                                 transferMode="Buffered"   
                                 transactionProtocol="OleTransactions"  
                                 hostNameComparisonMode="StrongWildcard"   
                                 maxBufferPoolSize="524288"  
                                 maxBufferSize="65536"   
                                 maxConnections="10"   
                                 maxReceivedMessageSize="2147483647"
                                 >
                    <security mode="None">
                        <transport protectionLevel="None" />
                    </security>
                </binding>
            </netNamedPipeBinding>
        </bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
            <baseAddressPrefixFilters>
                <add prefix="http://localhost:8733"/>
            </baseAddressPrefixFilters>
        </serviceHostingEnvironment>
    </system.serviceModel>
    <appSettings>
        <add key="countoffiles" value="7"/>
        <add key="logfilelocation" value="abc.txt"/>
    </appSettings>
</configuration>

修订的客户端C#代码:

var callback = new IpcCallbackAppToService();
InstanceContext context = new InstanceContext(callback);
NetNamedPipeBinding binding = new NetNamedPipeBinding();
binding.Security.Mode = NetNamedPipeSecurityMode.None;
EndpointAddress endpointAddress = new EndpointAddress("net.pipe://localhost/MyIpcAppToService");
var pipeFactory = new DuplexChannelFactory<IIpcAppToService>(context, binding, endpointAddress);
Program.HostIpcAppToService = pipeFactory.CreateChannel();
Program.HostIpcAppToService.Connect();
CommAppToService.IsPipeAppToService = true;

由于EventViewer是干净的,因此该服务不会抛出任何可以检测到的异常,仅显示OnStart()成功完成的消息。我知道系统会处理App.config文件,就像以前遇到错误时一样,Windows Event Viewer会一直抱怨,但现在不再。

以下是我使用的一些Microsoft文档:

netNamedPipeBinding

netNamedPipeBinding2

我确实尝试过IO Ninja,但是为\\.\pipe\MyIpcToServiceFile StreamPipe Listener指定了Pipe Monitor,但是即使我尝试连接也没有显示任何内容使用我的WinForms桌面应用程序,该应用程序随后会抛出“找不到管道侦听器”异常。

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

<endpoint address="net.pipe://localhost/MyIpcAppToService" binding="wsDualHttpBinding" bindingConfiguration="MyAppToServiceEndpointBinding" contract="MyIpc.IIpcAppToService"/>

确保服务地址的格式(绑定协议)与绑定类型相同。

  • TCP(net.tcp:// localhost:8000 / myservice)NetTcpBinding
  • IPC(net.pipe:// localhost / mypipe)NetNamedPipeBinding
  • Http / Https(http://localhost:8000/myservice
    Wshttpbinding,Wsdualhttpbinding,basichttpbinding

  • WebSocket(ws:// localhost:3434)Nethttp绑定

  • MSMQ(net.msmq:// localhost / private / myservice)NetMsmqBinding

我们应该使用NetnamedPipeBinding作为服务地址。请参考我的例子。


已更新
我在IIS中托管了一个使用NetNamedPipeBinding的wcf服务,希望它对您有用。
服务器(WCF服务应用程序)

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
}
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
}

Web.config(服务器端)

<system.serviceModel>
    <services>
      <service behaviorConfiguration="BehaviorMyService" name="WcfService1.Service1">
        <endpoint address="MyIpcAppToService"
                            binding="netNamedPipeBinding"
                            bindingConfiguration="EndpointBindingMyAppToService"
                            contract="WcfService1.IService1"
                                    />
        <endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="BehaviorMyService">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <netNamedPipeBinding>
        <binding name="EndpointBindingMyAppToService"
                         closeTimeout="00:01:00"
                         openTimeout="00:01:00"
                         receiveTimeout="00:10:00"
                         sendTimeout="00:01:00"
                         transactionFlow="false"
                         transferMode="Buffered"
                         transactionProtocol="OleTransactions"
                         hostNameComparisonMode="StrongWildcard"
                         maxBufferPoolSize="524288"
                         maxConnections="10"
                         maxReceivedMessageSize="2147483647"
                                 >
          <security mode="None">
            <transport protectionLevel="None" />
          </security>
        </binding>
      </netNamedPipeBinding>
    </bindings>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
    </serviceHostingEnvironment>
  </system.serviceModel>

启用WCF新功能。
enter image description here
enter image description here
IIS网站(启用net.pipe)
enter image description here
enter image description here
客户端(控制台应用程序)

  ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
    var result = client.GetData(34);
    Console.WriteLine(result);

客户端app.config(自动生成)
我使用http地址(服务元数据GET地址http://localhost:8733/Service1.svc?wsdl)来生成配置。

  <system.serviceModel>
        <bindings>
            <netNamedPipeBinding>
                <binding name="NetNamedPipeBinding_IService1">
                    <security mode="None" />
                </binding>
            </netNamedPipeBinding>
        </bindings>
        <client>
            <endpoint address="net.pipe://mynetpipe/Service1.svc/MyIpcAppToService"
                binding="netNamedPipeBinding" bindingConfiguration="NetNamedPipeBinding_IService1"
                contract="ServiceReference1.IService1" name="NetNamedPipeBinding_IService1" />
        </client>
    </system.serviceModel>

请随时告诉我是否有什么可以帮忙的。