【问题标题】:how to handle redirect from http response in c# code?如何在 c# 代码中处理来自 http 响应的重定向?
【发布时间】:2010-04-15 21:42:08
【问题描述】:

我有一个返回 url 的 http 请求调用。 如果我在 IE 中运行此 url,它会返回一个重定向到另一个页面并下载 excel 文件的页面。

如何在 c# Api 中抽象整个过程,它将在一个方法中处理 http 请求 + 响应 + 重定向 + file_downlaod 并最终返回文件或文件流。

感谢您的帮助。

【问题讨论】:

    标签: c#


    【解决方案1】:

    这里有一些 [过时的] 代码,它遵循所有重定向,直到它到达真实页面。您会希望使用更现代的 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;
    }
    

    【讨论】:

    • @YossiGeretz 用实际的 [但仍然相当旧的] 代码修复。
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 2018-07-15
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2017-03-07
    • 2018-02-20
    相关资源
    最近更新 更多