所以几周后我有一些时间来解决这个问题,事实证明,它与 ASP.NET 根本没有关系,这是 WebClient 的错。WebClient 在重定向之前清除其凭据,因此在这种情况下,原始请求是成功的,但是当 WebClient 尝试访问它已重定向到的页面时发生错误,因为目标也需要身份验证。
不幸的是,您不能仅通过属性切换此行为。所以我的解决方案看起来像这样。
//Credentials necessary for the request(s)
var cred = new NetworkCredential(username, password);
//Create initial request
var request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.Credentials = cred;
//Get response to first request
var response = (HttpWebResponse)request.GetResponse();
//Follow redirects
while (response.StatusCode == HttpStatusCode.Redirect && maxRedirects > 0)
{
//Build new URI for redirect target
var uri = response.ResponseUri;
url = String.Format("{0}://{1}:{2}{3}", uri.Scheme, uri.Host, uri.Port, response.GetResponseHeader("Location"));
//Create new request
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.Credentials = cred;
//Get new response
response = request.GetResponse() as HttpWebResponse;
maxRedirects--;
}
//Get the response's content
var sReader = new StreamReader(response.GetResponseStream());
string responseStr = sReader.ReadToEnd();
我没有使用 WebClient,而是使用 HttpWebRequest 和 HttpWebResponse 并手动遵循重定向。在发出请求之前,我设置了完成请求所需的凭据