Reputation: 824
My issue lies within the PostAsync
action of the HttpClient
.
A code excerpt used in my C# console app behaves totally different than the same code used in ASP.NET Core.
using (var httpClient = new HttpClient())
{
var parameters = new Dictionary<string, string> { { "various", "params" } };
var encodedContent = new FormUrlEncodedContent(parameters);
var response = await httpClient.PostAsync(url, encodedContent).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.OK)
{
var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
return responseContent;
}
}
Calling the method (GetData contains the upper code):
var unprocessedString = GetData("http://www.whatever.com/info.html").Result;
In the unprocessedString
I end up with a valid html string
The exact same code applied in my ASP .NET Core returns a completely different result.
The returned information looks like a huge JS script, I did check the fiddler request headers and the only difference is the Accept-Encoding: gzip, deflate
header being created by the ASP call, I did remove it and the results stays the same.
<html><head><meta http-equiv="Pragma" content="no-cache"/>
<script>
a huge javascript function
<noscript>Please enable JavaScript to view the page content.</noscript>
Upvotes: 2
Views: 2325
Reputation: 824
I did manage to find the issue.
My http - post initially gets to the upper mentioned JavaScript that redirects
my call to the seeked content ( This is what was happening when running the code from a .NET console app).
As far as I can see the ASP .NET Core implementation of the HttpClient
differs in behavior because the exactly same code (and inquired resource) behaved totally different because the redirect
never happened, thus the upper JS code ending up when I was reading info from that post.
This is how I've managed to fix it.
Firstly I declared an HttpClientHandler
with the AllowAutoRedirect
property to true
.
HttpClientHandler httpClientHandler = new HttpClientHandler { AllowAutoRedirect = true };
Then I just added this object to HttpClient
's constructor
HttpClient = new HttpClient(httpClientHandler);
Edit 1
I did manage to see a difference in the System.Net.Http
versions.
In the console app I have 4.0.0.0
In the .NET Core I have 4.1.1.1
Probably the latter version doesn't have the default behavior 4.0.0.0
had.
Upvotes: 3