我正在尝试使用HttpClient
来访问第三方SOAP WS。
[HttpGet]
public IActionResult Login()
{
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
HttpClient client = new HttpClient(httpClientHandler);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("POST"), myUrl);
request.Content = new StringContent(myXmlString, Encoding.UTF8, "text/xml");
request.Headers.Add("SOAPAction",https://actionNameOfWs);
HttpResponseMessage response = client.SendAsync(request).Result;
if(response.StatusCode == HttpStatusCode.OK) return new OkResult();
else return new ObjectResult(response.StatusCode);
}
此时所有内容都以TaskCanceledException: A task was canceled
中断,这实际上不是取消任务,而是连接超时。我可以使用SOAP UI在https
上发送相同的POST请求,因此连接到WS不是问题。我可以通过http
发送POST请求,上面的代码就好了。但是,一旦我尝试上面的代码通过https
发送POST,我就会遇到连接超时。那么,捕获的地方在哪里?
我的环境是: 操作系统:Linux Mint 16.04 .Net核心:1.0.1
答案 0 :(得分:1)
您可能正在混合异步和阻止呼叫。 .Result
是一个阻塞调用,可能导致死锁,当与异步调用混合时可能导致超时。使调用操作始终保持异步。
[HttpGet]
public async Task<IActionResult> Login() {
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
var client = new HttpClient(httpClientHandler);
client.Timeout = TimeSpan.FromSeconds(90);
var request = new HttpRequestMessage(HttpMethod.Post, myUrl);
request.Content = new StringContent(myXmlString, Encoding.UTF8, "text/xml");
request.Headers.Add("SOAPAction", https://actionNameOfWs);
var response = await client.SendAsync(request);
if(response.StatusCode == HttpStatusCode.OK) return Ok();
else return StatusCode((int)response.StatusCode);
}
我还建议你检查发送的原始请求及其响应。