c# - 客户端服务集成测试中的 CommunicationException
问题描述
我正在为我的 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;
没有任何改变。
我知道这可能与我从未在管道中使用任何证书这一事实有关,但我想知道为什么它会在我的本地机器上没有证书的情况下工作。另外,我真的不知道如何在管道中正确设置一个。有人可以帮我解决这个问题吗?
解决方案
确保使用以下标签正确指定配置,
<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
推荐阅读
- android - 如何在 Android 10 中替换 FileObserver?
- c# - Newtonsoft.Json.Linq.JObject '不包含 X 属性的定义
- javascript - 按下按钮后动画不重复
- python - 尝试运行 jupyter notebook 时模块“attr”中的错误
- arrays - VBA - 将长整数放入字节数组?
- c# - 不要破坏加载对象和游戏数据
- vuejs2 - 如何解决:“不能在异步函数之外使用关键字‘await’”
- python - 在维护行的同时连接列
- arrays - “按值传递的参数”CLRS 算法
- ios - ld:未找到架构 x86_64 Xcode 10.3 的符号