使用.net core 2.1 Web应用程序中的WCF服务

时间:2018-11-01 10:06:11

标签: c# wcf nettcpbinding .net-core-2.1

我有一个.net框架应用程序,该应用程序成功使用了WCF服务,并且当我尝试将设置复制到.net核心2.1 Web应用程序使用的.net标准2.0类库中时,出现各种错误取决于我的设置方式。

首先,这是有效的使用者配置:

<netTcpBinding>
<binding name="netTcpBinding_Service" closeTimeout="00:10:00" openTimeout="00:40:00" receiveTimeout="00:32:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647">
  <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
  <reliableSession ordered="true" inactivityTimeout="00:10:00" />
  <security mode="TransportWithMessageCredential">
    <message clientCredentialType="Certificate" algorithmSuite="Default" />
    <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
  </security>
</binding>
</netTcpBinding>
<behaviors>
  <endpointBehaviors>
    <behavior name="ClientBehavior">
      <clientCredentials>
        <clientCertificate findValue="Client" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
        <serviceCertificate>
          <defaultCertificate findValue="Server" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
          <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
        </serviceCertificate>
      </clientCredentials>
      <dataContractSerializer maxItemsInObjectGraph="2147483647" />
    </behavior>
  </endpointBehaviors>
</behaviors>
      <endpoint address="net.Tcp://localhost:8004/Service" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBinding_RACService" contract="ServiceInterfaces.IRACService" name="IService">
    <identity>
      <dns value="Server" />
    </identity>

方案1:尝试尽可能多地复制设置:

    private static NetTcpBinding CreateNetTcpBinding()
    {
        var security = new NetTcpSecurity
        {
            Message = new MessageSecurityOverTcp(),
            Transport = new TcpTransportSecurity()
        };
        security.Message.ClientCredentialType = MessageCredentialType.Certificate;
        security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
        security.Transport.SslProtocols |= SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;

        security.Mode = SecurityMode.TransportWithMessageCredential;

        var binding = new NetTcpBinding
        {
            CloseTimeout = new TimeSpan(0, 10, 0),
            OpenTimeout = new TimeSpan(0, 40, 0),
            ReceiveTimeout = new TimeSpan(0, 32, 0),
            Name = "NetTcpBinding",
            SendTimeout = new TimeSpan(0, 10, 0),
            MaxBufferPoolSize = 524288,
            MaxReceivedMessageSize = 2147483647,
            Security = security,
        };

        return binding;
    }

为此行获取异常:security.Message.ClientCredentialType = MessageCredentialType.Certificate; 例外:

  

{System.PlatformNotSupportedException:“ MessageCredentialType.None”以外的其他值不支持MessageSecurityOverTcp.ClientCredentialType。          在System.ServiceModel.MessageSecurityOverTcp.set_ClientCredentialType(MessageCredentialType值)


方案2:将MessageCrendentialType更改为“无”

private static NetTcpBinding CreateNetTcpBinding()
{
    var security = new NetTcpSecurity
    {
        Message = new MessageSecurityOverTcp(),
        Transport = new TcpTransportSecurity()
    };
    security.Message.ClientCredentialType = MessageCredentialType.None;
    security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
    security.Transport.SslProtocols |= SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;

    security.Mode = SecurityMode.TransportWithMessageCredential;

    var binding = new NetTcpBinding
    {
        CloseTimeout = new TimeSpan(0, 10, 0),
        OpenTimeout = new TimeSpan(0, 40, 0),
        ReceiveTimeout = new TimeSpan(0, 32, 0),
        Name = "NetTcpBinding",
        SendTimeout = new TimeSpan(0, 10, 0),
        MaxBufferPoolSize = 524288,
        MaxReceivedMessageSize = 2147483647,
        Security = security,
    };

    return binding;
}

private static EndpointAddress CreateEndpoint()
{
    var identity = new DnsEndpointIdentity("Server");
    var uri = new Uri("net.Tcp://localhost:8004/Service");
    var endpoint = new EndpointAddress(uri, identity);

    return endpoint;
}
public static ServiceProxy CreateClientProxy(string url)
{
    ServiceProxy racServiceProxy;
    racServiceProxyStore.TryGetValue(url, out racServiceProxy);

    try
    {
        if ((racServiceProxy != null) && (racServiceProxy.State == CommunicationState.Faulted ||
                                          racServiceProxy.State == CommunicationState.Closed))
        {
            racServiceProxy.Abort();
            racServiceProxy = null;
        }
        if (racServiceProxy == null)
        {
            CallBackProxy cb = new CallBackProxy();
            InstanceContext ctx = new InstanceContext(cb);

            var binding = CreateNetTcpBinding();
            var endpoint = CreateEndpoint();
            racServiceProxy = new ServiceProxy(ctx, binding, endpoint);
            racServiceProxy.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "Client");

        }
    }
    catch (InvalidOperationException ex)
    {
        throw;
    }
    catch (Exception ex)
    {
    }
    return racServiceProxy;
}

public void InvokeService(IWCFMessage message, OnStatusReceived onStatusReceived, OnResultReceived onResultReceived)
{
    try
    {
        Guid processId = ((WCFMessage)message).ProcessID;

        callBackProxy.AddEvents(onStatusReceived, onResultReceived, processId);

        if (this.State == CommunicationState.Opened || this.State == CommunicationState.Created)
        {
            if (this.State == CommunicationState.Created)
                this.ChannelFactory.Open();

            base.Channel.InvokeRACService(message);
        }
        else
        {
            throw new RacServiceProxyChannelException("Channel Faulted", (int)this.State);
        }
    }

this.ChannelFactory.Open();上遇到异常。如果我跳过这一行,则会在以下情况下出现异常:base.Channel.InvokeRACService(message); 例外:

  

{System.PlatformNotSupportedException:不支持NetTcpBinding.CreateMessageSecurity。          在System.ServiceModel.NetTcpBinding.CreateMessageSecurity()          在System.ServiceModel.NetTcpBinding.CreateBindingElements()          在System.ServiceModel.Channels.Binding.EnsureInvariants(字符串contractName)          在System.ServiceModel.Channels.ServiceChannelFactory.BuildChannelFactory(ServiceEndpoint serviceEndpoint,布尔useActiveAutoClose)          在System.ServiceModel.ChannelFactory.OnOpening()          在System.ServiceModel.Channels.CommunicationObject.System.ServiceModel.IAsyncCommunicationObject.OpenAsync(TimeSpan超时)处          在System.ServiceModel.Channels.CommunicationObject.OpenAsyncInternal(TimeSpan超时)处          在System.ServiceModel.ChannelFactory.EnsureOpened()          在System.ServiceModel.DuplexChannelFactory1.CreateChannel(InstanceContext callbackInstance,EndpointAddress地址,Uri通过)          在System.ServiceModel.ClientBase1.get_Channel()}


方案3:更改安全模式:security.Mode = SecurityMode.None;(在CreateNetTcpBinding方法中)

调用服务base.Channel.InvokeService(message);时获取异常 例外:

  

{System.ServiceModel.CommunicationException:套接字连接已中止。这可能是由于处理您的消息时出错,远程主机超出了接收超时或潜在的网络资源问题引起的。本地套接字超时为“ 00:09:59.8599605”。 ---> System.Net.Sockets.SocketException:现有的连接被远程主机强行关闭          在System.ServiceModel.Channels.SocketConnection.HandleReceiveAsyncCompleted()          在System.ServiceModel.Channels.SocketConnection.BeginReadCore处(Int32偏移量,Int32大小,TimeSpan超时,操作1 callback, Object state) --- End of inner exception stack trace --- at System.ServiceModel.Channels.SocketConnection.BeginReadCore(Int32 offset, Int32 size, TimeSpan timeout, Action 1回调,对象状态)          在System.ServiceModel.Channels.SocketConnection.BeginRead处(Int32偏移量,Int32大小,TimeSpan超时,Action 1 callback, Object state) at System.ServiceModel.Channels.DelegatingConnection.BeginRead(Int32 offset, Int32 size, TimeSpan timeout, Action 1回调,对象状态)          在System.ServiceModel.Channels.ConnectionHelpers.IConnectionExtensions.ReadAsync(IConnection连接,Int32偏移量,Int32大小,TimeSpan超时)          在System.ServiceModel.Channels.ConnectionHelpers.IConnectionExtensions.ReadAsync处(IConnection连接,Byte []缓冲区,Int32偏移量,Int32大小,TimeSpan超时)          在System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreambleAsync(IConnection连接,ArraySegment 1 preamble, TimeSpan timeout) at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnectionAsync(TimeSpan timeout) at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpenAsync(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.OnOpenAsyncInternal(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.System.ServiceModel.IAsyncCommunicationObject.OpenAsync(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.OpenAsyncInternal(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.Runtime.TaskHelpers.CallActionAsync[TArg](Action 1操作,TArg参数)处          在System.ServiceModel.Channels.CommunicationObject.OpenOtherAsync(ICommunicationObject其他,TimeSpan超时)处          在System.ServiceModel.Channels.ServiceChannel.OnOpenAsync(TimeSpan超时)处          在System.ServiceModel.Channels.CommunicationObject.OnOpenAsyncInternal(TimeSpan超时)处          在System.ServiceModel.Channels.CommunicationObject.System.ServiceModel.IAsyncCommunicationObject.OpenAsync(TimeSpan超时)处          在System.ServiceModel.Channels.CommunicationObject.OpenAsyncInternal(TimeSpan超时)处          在System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel通道,TimeSpan超时)处          在System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan超时,CallOnceManager级联)          在System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan超时)处          在System.ServiceModel.Channels.ServiceChannel.Call处(字符串操作,布尔单向,ProxyOperationRuntime操作,Object [] ins,Object [] outs,TimeSpan超时)          在System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(MethodCall methodCall,ProxyOperationRuntime操作)          在System.ServiceModel.Channels.ServiceChannelProxy.Invoke(MethodInfo targetMethod,Object [] args)       ---从之前引发异常的位置开始的堆栈结束跟踪---          在System.Reflection.DispatchProxyGenerator.Invoke(Object [] args)}

0 个答案:

没有答案