[英]how to handle redirect from http response in c# code?
我有一個返回 url 的 http 請求調用。 如果我在 IE 中運行此 url,它會返回一個重定向到另一個頁面並下載 excel 文件的頁面。
如何在 ac# Api 中抽象整個過程,它將在一個方法中處理 http 請求 + 響應 + 重定向 + file_downlaod 並最終返回文件或文件流。
謝謝您的幫助。
這是一些 [過時的] 代碼,它遵循所有重定向,直到它到達真實頁面。 您將希望使用更現代的 API 來發出 Web 請求,但原理是相同的。
/// \<summary\>
/// Follow any redirects to get back to the original URL
/// \</summary\>
private string UrlLengthen(string url)
{
string newurl = url;
bool redirecting = true;
while (redirecting)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newurl);
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0 (Windows; U;Windows NT 6.1; en - US; rv: 1.9.1.3) Gecko / 20090824 Firefox / 3.5.3(.NET CLR 4.0.20506)";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((int)response.StatusCode == 301 || (int)response.StatusCode == 302)
{
string uriString = response.Headers["Location"];
Log.Debug("Redirecting " + newurl + " to " + uriString + " because " + response.StatusCode);
newurl = uriString;
// and keep going
}
else
{
Log.Debug("Not redirecting " + url + " because " + response.StatusCode);
redirecting = false;
}
}
catch (Exception ex)
{
ex.Data.Add("url", newurl);
Exceptions.ExceptionRecord.ReportCritical(ex);
redirecting = false;
}
}
return newurl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.