Search code examples
authenticationhttp-redirectashx

Accessing XML via Web Handler results in 302 redirect


I'm trying to access an XML file via web handler. I am running into an infinite redirect (302) issue though. This is because cookies are not enabled. I'm not entirely certain what is causing it, but need some help figuring out what to do.

var url = context.Request.QueryString["xmlurl"];
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
hwr.Method = "GET";
hwr.MaximumAutomaticRedirections = 5;

//infinite redirect happens here
HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();

I suspect that the following cookies (found via Fiddler) are required:

ASP.NET_SessionId= ...
.ASPXAUTH= ...

These are created when the page is accessed via browser, but not with my web handler. Does anyone know how I can work around this?

The exact response I get back via web handler is:

<html>
<head>
   <title>Object moved</title>
</head>
<body>
   <h2>Object moved to <a href="removedForSO">here</a>.</h2>
</body>
</html>

Solution

  • The answer ended up being relatively simple. By adding

    hwr.CookieContainer = new CookieContainer();
    

    It allowed the server to attach cookies to the response, the redirect was then allowed and the final xml document was delivered.