Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

HttpClient follow 302 redirects with .NET Core

$
0
0

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:


Viewing all articles
Browse latest Browse all 285

Trending Articles