简体   繁体   中英

Why is my HttpWebRequest redirecting to Login page?

I have an HttpWebRequest to grab a session ID. I then get the cookie from the response, add it to a second request to get the page I need.

Using IIS/7.5, what are possible scenarios for this failing? I am using Fiddler, and get a 302 status. I am getting the ASPNET SessionID.

   CookieContainer myCookies = new CookieContainer();
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.secure.com/login.aspx");
    req.Method = "POST";
    req.Credentials = fileretrieve.Credentials;//Network credentials. 
    req.CookieContainer = myCookies;
    req.AllowAutoRedirect = true;

    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(req.Credentials.ToString());
    req.ContentLength = bytes.Length;
    System.IO.Stream os = req.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);
    os.Close();

    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

    HttpWebRequest xmlreq = (HttpWebRequest)HttpWebRequest.Create("https://www.secure.com/file");
    xmlreq.Method = "GET";
    xmlreq.KeepAlive = true;
    xmlreq.AllowAutoRedirect = true;
    xmlreq.CookieContainer = req.CookieContainer;


    HttpWebResponse xmlresp = (HttpWebResponse)xmlreq.GetResponse();

     string webpage;

    System.IO.StreamReader sr = new System.IO.StreamReader(xmlresp.GetResponseStream());
    webpage = sr.ReadToEnd();                    

I think it is failing because you are trying to use .Credentials property to authenticate in FormsAuthentication-based application. Credentials property would work for Basic or NTLM authentication, but not for Forms authentication, in that case you just need to POST expected fields to Login.aspx page in order to get Auth cookie back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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