HttpClient GetStringAsync 返回 301,但浏览器能够导航到正确的地址

res*_*p78 4 c# http-status-code-301 dotnet-httpclient

我认为HttpClient应该能够处理301错误代码,并重定向到正确的地址。但是,使用以下地址(https://www.npr.org/templates/rss/podcast.php?id=510298),它会抛出异常。不过浏览器能够正确处理它。只是想了解是否有出路或者我错过了什么。

HttpClient client = new HttpClient();

var s = await client
    .GetStringAsync("https://www.npr.org/templates/rss/podcast.php?id=510298");
Run Code Online (Sandbox Code Playgroud)

投掷

Test1 [0:00.779] Failed: System.Net.Http.HttpRequestException : Response 
status code does not indicate success: 301 (Moved Permanently).
System.Net.Http.HttpRequestException : Response status code does not 
indicate success: 301 (Moved Permanently).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.HttpClient.GetStringAsyncCore(Task`1 getTask)
   at XUnitTestProject1.UnitTest1.Test1() in 
   C:\Users\res\source\repos\test\XUnitTestProject1\UnitTest1.cs:line 13
Run Code Online (Sandbox Code Playgroud)

res*_*p78 6

我终于找到原因了。通常HttpClient会正确处理重定向,但如果来自https -> http. 这里就是这种情况。我被 chrome 浏览器的响应难住了,chrome 中显示的重定向 url 以 https 开头(https://www.npr.org/rss/podcast.php?id=510298),但实际重定向是http: //www.npr.org/rss/podcast.php?id=510298

有一个解释https://github.com/dotnet/runtime/issues/21446#issuecomment-298323133