How to get Cookie of Request Header after reponse in C# - c#

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.

Related

c# RestSharp: Adding and delete cookie because Statuscode 403

i am currently try to get information of an external API using RestSharp (Version 107.1.2). Unfortunately, in every request I get response Status Code 403 "Forbidden". I now have contact to the provider and he told me, to delete all cookies first and then add the cookie "SMCHALLENGE=YES".
I tried this in RestSharp, but when using the client.AddCookie extension, I receive ArgumentException. I now found another option, to add the cookie in header, but this doesn't work either.
Do you have an idea, how to delete all cookies and then add the SMCHALLENGE cookie?
var client = new RestClient("https://test.de/api/token");
string resource = null;
client.Authenticator = new HttpBasicAuthenticator("testUser", "testPW");
string apiKey = null;
var request = new RestRequest(resource, Method.Get);
//Following execution throws System.ArgumentException: "The {0} parameter cannot be an empty string. Parameter name: cookie.domain"
//client.AddCookie("SMCHALLENGE", "YES");
request.AddHeader("Cookie", "SMCHALLENGE=YES");
var response = client.ExecuteAsync(request);
response.Wait();
RestResponse rr = response.Result;
Thank you very much!
Cookies aren't headers. You need to add your cookies to the RestClient own cookie container. Cookies that are returned in the response will also be available in the cookie container. There's a function on RestClient to do that as a shortcut.
var client = new RestClient("https://test.de/api/token");
client.AddCookie("SMCHALLENGE", "YES");
You can also work with the cookie container:
client.CookieContainer.Add(new Cookie(...));
You'd need to avoid creating a new RestClient instance for each request. This way you'd also keep the cookies across requests.

HttpClient is modifying my original request to change domains

I have some code that is making a Server2Server call using an HttpClient. Here is some quick code
Code to make a request
private HttpRequestMessage GetRequest(Uri uri, NameValueCollection headers)
{
var method = HttpMethod.Get;
var request = new HttpRequestMessage(method, uri);
foreach (string v in headers)
{
var success = request.Headers.TryAddWithoutValidation(v, headers[v]);
if (!success)
{
// log something ( no logs are appearing )
}
}
return request;
}
Code to make the request
private void AsyncCallUrl(Uri url, NameValueCollection headers)
{
object result1 = null;
var handler = new HttpClientHandler() { AllowAutoRedirect = false };
using (HttpClient client = new HttpClient(handler))
{
var request = GetRequest(url, headers);
using (HttpResponseMessage response = client.SendAsync(request).Result) // when this line is executed the request object's domain is changed to something else
{
using (HttpContent content = response.Content)
{
result1 = content.ReadAsStringAsync().Result;
}
}
}
I've verified that the request object is created appropriately with the proper domain. I've also verified that the network traffic is going to the wrong domain, even the request object shows the new bad domain. What I don't is why this is happening. I've even set the AllowAutoRedirect to false
NOTE: As a note I notice that if I use GetAsync instead of SendAsync the domain change doesn't happen. However this is not an ideal solution as in order to add headers I would need to add them to the HttpClient itself and this code lives on an IIS server and I don't want to make a new client for every request
So, with SendAsync the value of the Host header of the request is determined by the uri parameter... However it is possible to override the Host header through the Headers property of the request.
It's highly likely that the NameValueCollection headers that you are blindly injecting into the request's headers contains an entry for Host which is different to that which you supplied in the Uri.
As an aside, this behaviour can be useful, if (for instance) you were to discover that the DNS performance of HttpWebRequest (the business end of HttpClient on Windows) is sub-standard. I've bypassed .Net/Windows DNS by using a third party library to look up the IP of the host, rewriting the Uri to use the IP address in place of the host name, then setting the Host header on the outgoing request back to the original host name.

C# HttpWebRequest session loss [duplicate]

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

HttpCookie to Cookie - how to deal with missing Domain?

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?

C# httpwebrequest cookies

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.

Categories

Resources