【问题标题】:CommunicationException in client-service integration test客户端服务集成测试中的 CommunicationException
【发布时间】:2018-09-20 06:26:00
【问题描述】:

我正在为我的 WCF 服务进行集成测试,其中我的测试客户端正在向自托管服务发出请求。

我的 WCF 服务设置:

var binding = new BasicHttpBinding {Security = {Mode = BasicHttpSecurityMode.Transport}};
var endpointAddress = new EndpointAddress("https://localhost:44398/MyService.svc");
var host = new ServiceHost(typeof(MyService), endpointAddress.Uri);
host.AddServiceEndpoint(typeof(WcfServices.Contracts.IMyService),
binding, endpointAddress.Uri);
host.Open();

还有我的客户来电:

var client = new MyServiceClient(binding, endpointAddress);

// Act

Contract.MyResult result;
try
{
    result = actMethod.Invoke(sut);
}
finally
{
    client.Close();
    if (host.State == CommunicationState.Opened)
        host.Close();
    else
        host.Abort();
}

在执行测试之前,我运行这个 PowerShell 脚本:

$whoami = WHOAMI
netsh http add urlacl url=https://+:44398/MyService.svc/ user=$whoami

在我的本地机器上一切正常,但是当它在 Azure DevOps 中使用我的管道构建时,并且运行这个特定的测试时,我得到:

System.ServiceModel.CommunicationException:向https://localhost:44398/MyService.svc 发出 HTTP 请求时出错。这可能是由于在 HTTPS 情况下未使用 HTTP.SYS 正确配置服务器证书。这也可能是由于客户端和服务器之间的安全绑定不匹配造成的。

---- System.Net.WebException : 底层连接已关闭:发送时发生意外错误。

-------- System.IO.IOException : Unable to read data from the transport connection: 一个现有的连接被远程主机强行关闭。

------------ System.Net.Sockets.SocketException : 现有连接被远程主机强行关闭

另外,我已经尝试将此添加到我的测试中:

if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls))
    ServicePointManager.SecurityProtocol =
        SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

没有任何变化。

我知道这可能与我从未在管道中使用过任何证书这一事实有关,但我想知道为什么它会在我的本地计算机上没有证书的情况下工作。另外,我真的不知道如何在管道中正确设置一个。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: c# wcf integration-testing azure-pipelines


    【解决方案1】:

    确保使用以下标签正确指定配置,

    <serviceBehaviors>
          <behavior name="nameofBehaviour">
            <serviceMetadata httpsGetEnabled="true"/>
          </behavior>
        </serviceBehaviors>
    

    此外,您可以尝试在代码中添加以下行。

    System.Net.ServicePointManager.SecurityProtocol =
     System.Net.SecurityProtocolType.Tls12;
    
    System.Net.ServicePointManager.SecurityProtocol =
       System.Net.SecurityProtocolType.Tls12 | Tls1.1 | Tls1.0
    

    【讨论】:

    • 遗憾的是,什么都没有改变,仍然是同样的异常。
    • 可以尝试使用自签名证书!
    • 我在构建过程中发布了一个New-SelfSignedCertificate -DnsName "https://localhost:44398/MyService.svc/" -CertStoreLocation "cert:\LocalMachine\My",但无济于事。我做错了吗?
    • DnsName 应该是本地主机。你应该将它绑定到构建机器上的端口。您也可以通过net http show sslcert 查看本地机器上绑定了哪个证书。
    猜你喜欢
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多