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

问题描述 投票:0回答:1

我以为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");

投掷

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
c# dotnet-httpclient http-status-code-301
1个回答
0
投票

我终于找到了原因。通常,HttpClient将正确处理重定向,但如果它来自https-> http,则不会处理重定向。就是这种情况。 chrome浏览器的响应让我很困惑,chrome中显示的重定向URL以https开头。

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

© www.soinside.com 2019 - 2024. All rights reserved.