HttpClient follow 302 redirects with .NET Core

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:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.