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 en开发者_JAVA技巧try 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?
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?
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);
}
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.
精彩评论