There is a task to contact the server, to receive a response, then in the same session to contact the server again. This is necessary because authorization is performed this way. My code gives an error on the second GetRequestStream that the stream is not writable. What should I do to save the session and I could send a second request during this session? The first server response is correct, indicating that I have successfully logged in.

public ActionResult Regs() { string url = "url"; string postData = "postData"; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "POST"; webRequest.ContentType = "text/xml"; using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream())) { requestWriter2.Write(postData); } HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse(); string responseData = string.Empty; using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream())) { responseData = responseReader.ReadToEnd(); } postData = "second_postData"; using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream())) { requestWriter2.Write(postData); } resp = (HttpWebResponse)webRequest.GetResponse(); using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream())) { responseData = responseReader.ReadToEnd(); } ViewBag.RD = responseData; return PartialView(); } 

    1 answer 1

    It turned out that the problem is solved simply. I make a cookie container:

     CookieContainer cookieContainer = new CookieContainer(); 

    I tie it to the first request:

     webRequest.CookieContainer = cookieContainer; 

    Then, after receiving the answer, I create a second request and attach the same container to it:

     HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create(url); webRequest1.CookieContainer = cookieContainer; 

    Everything works out normally, the answers are correct.