Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read local cookies

I have an ASP.NET web application that stores a HTTP cookie when a certain action has been performed (e.g. a link has been clicked). Now, I am creating a standalone C# app which needs to watch the cookies folder and recognise when a cookie entry has been created by my web application and read the contents of the cookie.

Could anyone please guide me on how to do this in C# or show sample code?

like image 206
Glory Avatar asked Jul 28 '10 22:07

Glory


People also ask

How do I open a local cookie file?

In such a browser as Mozilla Firefox, you can see the cookies in the browser settings. For this, you just need to click on the Open menu > Web Developer. In Google Chrome you can find cookie files entering chrome://settings/content/ Cookies in the address bar.

How do you read data from cookies?

Read cookie using JavaScript: This function retrieves the cookie data stored in the browser. The cookie string is automatically encoded while sending it from the server to the browser. Hence it needs to be decoded before the actual data can be retrieved.

How do you view cookies?

Android ChromeStart Chrome, then open the options menu and scroll down to 'Settings', followed by 'Site setttings'. To view and delete cookies, select 'Data stored' - you will see a list of all the sites which have stored cookies on your device.


2 Answers

I can't help thinking that is simply the wrong way to do it... and it reaks of security abuse. Is there no better way you could do this? Perhaps hosting the page in a WebBrowser control and using an ObjectForScripting object (of your devising) so you can talk to the C# app from javascript?

like image 94
Marc Gravell Avatar answered Sep 26 '22 00:09

Marc Gravell


You should be able to PInvoke InternetGetCookie.

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
protected static extern bool InternetGetCookie(
    string url,
    string name,
    StringBuilder cookieData,
    ref int length);

You can then call InternetGetCookie like below assuming you are using the Rest Starter Kit.

StringBuilder cookieBuffer = new StringBuilder(1024); 
int size = 1024; 
bool bSuccess = InternetGetCookie("domain uri", "cookie_name", cookieBuffer, ref size); 
if (!bSuccess) 
{ 
    Int32 err = Marshal.GetLastWin32Error(); 
    //log err
} 
if (cookieBuffer != null && (cookieBuffer.Length > 0)) 
{ 
    Microsoft.Http.Headers.Cookie cookie = Microsoft.Http.Headers.Cookie.Parse(cookieBuffer.ToString()); 
    HeaderValues<Microsoft.Http.Headers.Cookie> requestCookies = new HeaderValues<Microsoft.Http.Headers.Cookie>(); 
    requestCookies.Add(cookie); 
}
like image 20
Wil P Avatar answered Sep 25 '22 00:09

Wil P