1

I have a http request call that return a url . If I run this url in IE it returns a page that redirects to a another page and downloads the excel file.

How can I abstract this whole process in a c# Api tha will deal with http request + response + redirect + file_downlaod in a method and evetually return the file or the file stream.

thanks for the help.

2 Answers 2

2

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.

/// \<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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@YossiGeretz Fixed with the actual [but still rather old] code.
1

You may consider using WebRequest / WebClient classes.

Here you have some examples.

http://msdn.microsoft.com/en-us/library/system.net.webrequest%28VS.80%29.aspx

http://www.c-sharpcorner.com/UploadFile/mahesh/WebRequestNResponseMDB12012005232323PM/WebRequestNResponseMDB.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.