views:

68

answers:

3

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?

+2  A: 

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); 
}
Wil P
+4  A: 

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?

Marc Gravell
@Marc, Good point. OP, is there any reason why you have to store the value on the client? What about storing the value on the server and having the client app pull it down via a service? Esp if the client app has no real need for WebBrowser control.
Wil P
I need my app to perform a certain action when a link has been clicked on in my website. So I thought the best way to do this would be for the app to watch for cookies and for the website to store a cookie when a link has beenclicked on. Is there a better way?
Glory
A: 

There is another thing you can do that could cause your local application to be invoked by the clicking of a link. You'd need to register an application to a URL protocol as seen here. Here is a tutorial and sample app you can look at.

Doing this has it's own set of security implications. However, it is an easy way to invoke your application from the web page and it allows you to pass data via command line params.

Wil P