The HttpClient in .NET Core will not automatically follow a 302 (or 301) redirect. You need to specify that you allow this. use the HttpClientHandler to do this:
private static HttpClient _httpClient = new HttpClient(
new HttpClientHandler
{
AllowAutoRedirect = true,
MaxAutomaticRedirections = 2
}
);
Now your code will follow up to 2 redirections. Please note that a redirect from a HTTPS to HTTP is not allowed.
You can now grab the contents even from a redirected URL:
public static async Task<string> GetRss()
{
// The /rss returns a 301 Moved Permanently, but my code will redirect to
// /feed and return the contents
var response = await _httpClient.GetAsync("https://briancaos.wordpress.com/rss");
if (!response.IsSuccessStatusCode)
throw new Exception($"The requested feed returned an error: {response.StatusCode}");
var content = await response.Content.ReadAsStringAsync();
return content;
}
MORE TO READ:
- Using C# HttpClient from Sync and Async code by briancaos
- C# HttpClient POST or PUT Json with content type application/json by briancaos
- HttpClient does not follow 302 redirects from GitHub