I'm not sure how much of my code here is relevant in figuring out the problem so I'll start from the top. I use Injection to create an azure web job program and it looks like this:
static void Main()
{
try
{
//CompositionRoot code omitted - however, this part works.
CompositionRoot().Resolve<Application>().Run();
}
catch (Exception ex)
{
//some logging
}
}
Then my Application Run method looks like this:
public void Run()
{
var result = _someService.SomeMethod(new SomeParam()).GetAwaiter().GetResult();
}
Then the service is calling out to a third party api and makes the call as such:
public async Task<int> SomeMethod(SomeModel model)
{
var kvp = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("api_key", "api_key"),
}
var result = await FormPostStreamAsync(kvp, "some uri", null, CancellationToken.None);
var json = result.Content.ReadAsStringAsync().Result;
}
public async Task<HttpResponseMessage> FormPostStreamAsync(IList<KeyValuePair<string, string>> content, string uri, IList<KeyValuePair<string, string>> headers, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested) return null;
if (headers == null) headers = new List<KeyValuePair<string, string>>();
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, uri))
using (var httpContent = CreateKvpHttpContent(content))
{
client.Timeout = TimeSpan.FromMinutes(30);
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
request.Content = httpContent;
return await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
}
When I call the above code: var json = result.Content.ReadAsStringAsync().Result;
I get an exception:
The request was aborted: The request was canceled.
I can't figure out why. I'm not calling cancel anywhere and it is not timing out because this happens instantly and I put a timeout of 30 minutes just to see if it makes a difference. The result object has values, it has headers and a status code of 200. So It seems that the post request has worked, but when it tries to parse the response, it throws that exception. Does anyone has an idea where I went wrong?
If I look at the response via fiddler I see the following:
{"result_code":0,"result_message":"Some message","result_output":"json"}
EDIT: After more testing, I have found that if I call this same code (same parameters) (without making any changes) from a website then it works. However, if I call this from the application that I showed above then it does not.