I'm using the below code to reuse the sessions.
Will I get the same session id on the grabUrl response cookies?
How do I know if both requests are using the same session/cookie?
Thanks.
CookieContainer cookCon = new CookieContainer();
Httpwebrequest loginReq = (httpwebrequest) loginReq.create(loginurl);
loginReq.cookiecontainer = cookCon;
... All the response stuffs
Httpwebrequest grabReq = (httpwebrequest) grabReq.create(grabUrl);
grabUrl.cookiecontainer = cookCon
When I add in below code to see the container contents, it shows that there is a session id:
foreach (Cookie cook in cookieContainer.GetCookies(new Uri(loginurl)))
{
Console.WriteLine("Cookie_Get_Container:");
Console.WriteLine("====================================================");
Console.WriteLine("String: {0}", cook.ToString());
Console.WriteLine("====================================================");
}
So I added cookies to the login response:
cookieContainer.Add(new Uri(domainUrl), loginRes.Cookies);
I am not able to get the session id when I try to get from the cookieContainer.grabRes.Cookies.
Any advise?
Since you are not showing code that grabs session cookie from first response I assume that you are not and the answer is "no, new session is created for second requset".
You want to get session ID (and other) from first response and set them on new requests (i.e. by adding them to the container).
Side note: depending on authenitcation method the information to authenticate the next requests (different from session ID) may not come in cookies.
Related
I am trying to perform a get request to https://www.footlocker.dk/. I need to obtain the session that is created, when visiting this url.
I perform the request as following:
string url = "https://www.footlocker.dk/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = null;
request.CookieContainer = new CookieContainer();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
foreach (Cookie cookie in response.Cookies)
{
Console.WriteLine("name=" + cookie.Name);
Console.WriteLine("value=" + cookie.Value);
Console.WriteLine("path=" + cookie.Path);
Console.WriteLine("domain=" + cookie.Discard);
}
}
However it doesnt return me any cookies..
I need these cookies, when I want to go ahead and make a post request afterward, to perform a specific action on this url.
Regards!
Check the response payloads:
You'll see that the call: https://www.footlocker.dk/api/session?timestamp=1611587725706 has a response header like this:
set-cookie: JSESSIONID=orfy8ma22lox1nd8wxdyf8h4e.fzcxwefapipdb018883; Path=/; HTTPOnly
The https://www.footlocker.dk/ sets no such cookies. Bear in mind that if you go throug the calls, you'll see multiple cookie sets, and you can't be absolutely sure which one you need to make things work, though I believe that you can get the cookie you need just by making the session call.
The final cookie definition looks like this:
I want to get cookies "Request Header" not "Reponse Header" of links "https://www.udemy.com/join/login-popup/"
I have used WebRequest and HttpClient but when I did not see Cookie debug in it
Please help me write it in C # I find trying to find every possible way but I still have not found.
Using System.Net.Http.HttpClient for example, we can get cookies like following:
var myClientHandler = new HttpClientHandler();
myClientHandler.CookieContainer = new CookieContainer();
var client = new HttpClient(myClientHandler);
var response = await client.GetAsync("https://www.udemy.com/join/login-popup/");
var cookieCollection = myClientHandler.CookieContainer.GetCookies(new Uri("https://www.udemy.com/join/login-popup/"));
foreach (var cookie in cookieCollection.Cast<Cookie>())
{
Debug.WriteLine(cookie);
}
HttpClient saves cookies that are sent by a server and automatically add them to subsequent requests to that URI within the same app container. So if we didn't modify cookies manually, the cookies in "Request Header" should be the same as what returned in previous reponse.
I am creating an application for data retrieval from the web page. The page is password protected and when the user logs in the cookie is created.
In order to retrieve the data the application first has to log in: make web request with username and password and store the cookie. Then when the cookie is stored it has to be added into the headers of all requests.
Here is the method which makes requests and retrieves the content:
public void getAsyncDailyPDPContextActivationDeactivation()
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(dailyPDPContextActivationDeactivation);
IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
string responseText = responseStreamReader.ReadToEnd();
}
}
Does anyone know how to modify this method in order to add a cookie into the header?
I would be also thankful if anyone suggested a way to store cookie from the response (when the application makes a request http:xxx.xxx.xxx/login?username=xxx&password=xxx the cookie is created and has to be stored for future requests).
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest.CookieContainer = cookieContainer;
Then you reuse this CookieContainer in subsequent requests:
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest2.CookieContainer = cookieContainer;
Use the CookieContainer or you could use a CookieAwareWebClient
I am creating a proxy page in ASP .NET (I need to get around cross-site scripting limitations). I need the Page_Load handler to send out an HttpWebRequest based on the incoming request to this page.
var request = (HttpWebRequest)WebRequest.Create(urlToProxy);
request.Method = "GET";
request.GetResponse();
I'm running into some authentication problems (yes, I do set request.Credentials correctly, it's just not shown here), however, so I'd like to forward cookies from the incoming request (that hits my proxy page) to this outgoing request. You would think this would be straightforward:
request.CookieContiner = Request.Cookies;
However, this doesn't work. The outgoing HttpWebRequest uses HttpCookies and the incoming HttpRequest uses Cookies. These classes have no inheritance or interface relationship (indeed one is in System.Net, the other in System.Web.)
I've tried to copy the HttpCookies into Cookies and then add them to the CookieContainer, but I can't get this to work either.
public static IEnumerable<Cookie> ToCookies(this HttpCookie cookie)
{
var cookies = new List<Cookie>(cookie.Values.Count);
foreach (String key in cookie.Values)
{
cookies.Add(new Cookie()
{
Domain = cookie.Domain,
Expires = cookie.Expires,
HttpOnly = cookie.HttpOnly,
Name = cookie.Name,
Path = cookie.Path,
Secure = cookie.Secure,
Value = cookie.Values[key]
});
}
return cookies;
}
...
var cookieContainer = new CookieContainer();
foreach(var httpCookie in Request.Cookies)
{
foreach(var cookie in httpCookie.ToCookies())
{
cookieContainer.Add(cookie); //Exception thrown here
}
}
The exception being thrown says that a Cookie cannot be added that has a null "Domain". Apparently, some of the HttpCookies have null "Domain" properties.
Does anyone have any suggestions on the best way around this problem turning HttpCookie into Cookie? I'd like whatever solution I use with to be as general purpose as possible (and thus not involve hardcoding known domains into the new Cookies.)
Even better, is there an easier way to do what I want simply using the HttpRequest class rather than the HttpWebRequest class?
I am using a web service that requires authentication from .NET (Visual Studio 2010). According to the documentation, you first request a session identifier from the first web service. I can do that with no problem. Then you are supposed to call the second web service for actually performing your query, passing the session identifier in a cookie. Here is my sample code:
AuthenticateService authenticate_service = new AuthenticateService();
string session_identifier = authenticate_service.Authenticate();
SearchService search_service = new SearchService();
search_service.CookieContainer = new CookieContainer();
Cookie cookie = new Cookie("Cookie", "SID=" + session_identifier, null, search_service.Url);
search_service.CookieContainer.Add(cookie);
search_service.Test();
However, I am getting the following exception on the last line:
System.Web.Services.Protocols.SoapException was unhandled
Message=Session ID cookie value cannot be null or empty string - It is required that the high level Web service client program participate in the session initialized by the server.
Does anybody know how to properly send a cookie with a session ID to a web service?
Just figured it out...
It all had to do with the domain parameter of the Cookie constructor. I was passing search_service.Url because I wasn't sure what it was supposed to be. Apparently it should have been something like "search.google.com". When I passed that to the constructor instead, everything started working as expected.
I found this somewhere along the line. It is a cookie-aware web-client that I have been using. This allows me to have the ease of use of WebClient and pass cookies.
public class CookieAwareWebClient : WebClient
{
private CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}
Then you can just use the WebClient methods and the cookie is passed automatically after you authenticate.
Example code:
CookieAwareWebClient webClient = new CookieAwareWebClient();
NameValueCollection data = new System.Collections.Specialized.NameValueCollection();
data["user"] = "myusername"; //now holds a user=username map
byte[] response = webClient.UploadValues("http://localhost:8080/somewebservice/auth/","POST", data); //point to the webservice authentication URI
Now you can use webclient.UploadFile or UploadValues or whatever you want assuming that the previous authentication was OK.