简体   繁体   中英

Asp.net core, HttpClient to reach SOAP service with POST request

I'm trying to reach 3rd party SOAP WS using HttpClient .

[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);
}

At this point everything breaks with TaskCanceledException: A task was canceled , which is not really a task cancel, but a connection timeout. I can send the same POST request over https with SOAP UI just fine, so connection to WS is not a problem. I can send POST request over http with code above just fine. But once I'm trying code above to send POST over https , I'm getting connection timeout. So, where's the catch?

My environment is: OS: Linux Mint 16.04 .Net Core: 1.0.1

You may be mixing async and blocking calls. .Result is a blocking call that can lead to deadlocks which may be causing the timeout when mixed with async calls. Make the calling action async all the way through.

[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);
}

I would also suggest that you inspect the raw request being sent and its response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM