Click here to Skip to main content
15,616,432 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have code in Python for accessing a web server that requires authentication before accessing other resources. But I need to do it in C#. Is there around any C# example operating in a similar way as Python's request request library?

Thanks a lot in advance.

Python code is similar to this one below:
mySession = requests.Session()
url = 'https://some_plce/login'
login_info = { "who": "me", "pwd": "don't give it"}, login_info)

ans = mySession.get(
    'param1': __some_param1,
    'param2': __some_param2

my_precious_data = ans.content.decode('utf8').replace("'", '"')

What I have tried:

I've already been able to execute the login step (with POST), using the code below, but I need to GET the data.

string Uri = "https://some_plce/login";
string POSTData = $"who={Usr}&pwd={pwd}"; // Usr & Pwd are function parameters.
byte[] rawPOSTData = Encoding.UTF8.GetBytes( POSTData );

WebRequest request = WebRequest.Create( Uri );
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = rawPOSTData.Length;

using (Stream dataStream = request.GetRequestStream())
    dataStream.Write( rawPOSTData, 0, rawPOSTData.Length );

using (WebResponse response = request.GetResponse())
    // Do some checks.
Updated 15-Apr-20 6:12am
F-ES Sitecore 15-Apr-20 12:01pm    
Change "POST" to "GET" in the method and put the param on the POSTData param on the URL. If you google how to do a GET with WebRequest you'll find examples.
V.Lorz 15-Apr-20 12:37pm    
Hi F-ES Sitecore, thanks for your comment.
The first request (login) requires a POST, not a GET. And the second requires a session id returned by the server on this first login request. Maybe my question was not self explanatory, sorry for that.
I've already solved the issue, see my comment below under MadMyche's solution.

1 solution

The session is actually a server-side item, and how it is kept track of is via Cookies. IN the C# environment, you would attach a CookieContainer to the request to let the server know you accept cookies
var request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = new CookieContainer();
And then when you do get the response, there will be a Cookies property which will be a collection of all the cookies that were sent.
var response = (HttpWebResponse) request.GetResponse()
Save the cookies, and add them back in when you make followup requests

HttpWebRequest.CookieContainer Property (System.Net) | Microsoft Docs[^]
HttpWebResponse.Cookies Property (System.Net) | Microsoft Docs[^]
Share this answer
V.Lorz 15-Apr-20 12:29pm    
Thanks a lot for taking your time to answer, @MadMyche. Here what I did, and worked for me:

CookieContainer Cookies = new CookieContainer();
Cookies.Add( new Cookie( "thesessionidcookiename", SessionId, "", "the server domain" ) );

HttpWebRequest request = HttpWebRequest.CreateHttp( $"{Uri}?{POSTData}" );
request.Method = "GET";
request.CookieContainer = Cookies;

using (WebResponse response = request.GetResponse())

At the end the server is using a java servlet engine, so the session id can also be given as part of the url. There is no session id cookie, neither any cookie at all, in the login response, it comes as part of its headers.
Member 15634651 13-May-22 4:09am    
Hello, I have exactly the same issue and I struggled for weeks to find a solution.

in my case I have this python code:
``` session = requests.Session()

params = {
"email": f"{email}",
"password": f"{password}"

headers = {'Content-Type': 'application/x-www-form-urlencoded'}'{url}/login', data=urllib.parse.urlencode(params), headers=headers, verify=False)
return session.cookies.get_dict()['session']

I tried extracting a solution from your case, and I came out with this:

``` string url= "url"
string POSTData = $"email={email}&password={password}";

CookieContainer Cookies = new CookieContainer();
Cookies.Add(new Cookie("thesessionidcookiename", "", "", "the server domain"));

HttpWebRequest request = HttpWebRequest.CreateHttp($"{url}?{POSTData}");
request.ContentType = "application/x-www-";
request.Method = "POST";
request.CookieContainer = Cookies;

using (WebResponse response = request.GetResponse())
{ }

Do you have any idea of a proper solution to my case ? Thanks in advance

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900