简体   繁体   English

如何在 c# 代码中处理来自 http 响应的重定向?

[英]how to handle redirect from http response in c# code?

I have a http request call that return a url .我有一个返回 url 的 http 请求调用。 If I run this url in IE it returns a page that redirects to a another page and downloads the excel file.如果我在 IE 中运行此 url,它会返回一个重定向到另一个页面并下载 excel 文件的页面。

How can I abstract this whole process in ac# Api tha will deal with http request + response + redirect + file_downlaod in a method and evetually return the file or the file stream.如何在 ac# Api 中抽象整个过程,它将在一个方法中处理 http 请求 + 响应 + 重定向 + file_downlaod 并最终返回文件或文件流。

thanks for the help.谢谢您的帮助。

Here is some [dated] code that follows all redirects until it hits a real page.这是一些 [过时的] 代码,它遵循所有重定向,直到它到达真实页面。 You'll want to use more modern APIs to make web requests but the principle is the same.您将希望使用更现代的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM