简体   繁体   中英

Accessing ASP.NET_SessionId on HttpWebResponse C#

I'm trying to get ASP.NET_SessionId from a HttpWebResponse but it seems that no such data comes on the response. Basically I'm trying to simulate some steps over some pages, where authentication is required. The problem is not in the authentication, my problem is to get ASP.NET_SessionId after the authentication so I can use it in my future requests/steps.

From Chrome on developer tools > network, I can see the ASP.NET_SessionId on the headers, but it does not come in my HttpWebResponse. Any ideia why this is happening? There is my code:

 var httpWebRequest              = (HttpWebRequest) WebRequest.Create(url);
 httpWebRequest.UserAgent        = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36";             httpWebRequest.Method           = "POST";
 httpWebRequest.ContentType      = "application/x-www-form-urlencoded";
 httpWebRequest.ContentLength    = 0;
 var httpWebResponse             = (HttpWebResponse) httpWebRequest.GetResponse();

After my request I should see a ASP.NET_SessionId header Set-Cookie, but no luck. Any ideia?

I've seen some people say that

httpWebResponse.Headers["ASP.NET_SessionId"]

or

httpWebResponse.Headers["SESSION_ID"]

should work but no, no session id header is set nor any Cookie.

After many research, the answer was here

Basically we have to keep the same CookieContainer object reference across all requests. I was extracting some Set-Cookie from the responses and adding them into my requests, but now I don't need to do anything, CookieContainer manages all of it transparently.

Set-Cookie from responses are set on CookieContainer of your request . It's the way they found to resolve possible security issues, so don't lose more time and just keep a reference to your CookieContainer because you will not be able to access session id (and you don't need it).

There's the example of my code now.

var cookieContainer = new CookieContainer();

var httpWebRequest1 = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest1.CookieContainer = cookieContainer;

// do the request and some logic

var httpWebRequest2 = (HttpWebRequest) WebRequest.Create(anotherUrl);
httpWebRequest2.CookieContainer = cookieContainer; // same cookieContainer reference

Everything is working great now, hope it helps someone.

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