我正在开发一个基于WPF的应用程序,其中涉及到与Twitter API的交互。为了展示Twitter认证页面,我使用了WPF Web-Browser控件。我能够成功地登录并使用Twitter API。但是我的问题是,我需要清除Web浏览器的cookies以实现注销功能。有没有办法在WPF Web-Browser中清除会话cookie?
我正在开发一个基于WPF的应用程序,其中涉及到与Twitter API的交互。为了展示Twitter认证页面,我使用了WPF Web-Browser控件。我能够成功地登录并使用Twitter API。但是我的问题是,我需要清除Web浏览器的cookies以实现注销功能。有没有办法在WPF Web-Browser中清除会话cookie?
WebBrowser
不允许您修改(删除)现有的会话cookie。这些会话cookie可以防止多用户单设备体验成功。Marshal
服务。下面是一个完整的解决方案,可以放入您的项目以抑制会话cookie的持久性。public static partial class NativeMethods
{
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
private const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 81;
private const int INTERNET_SUPPRESS_COOKIE_PERSIST = 3;
public static void SuppressCookiePersistence()
{
var lpBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)));
Marshal.StructureToPtr(INTERNET_SUPPRESS_COOKIE_PERSIST, lpBuffer, true);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, lpBuffer, sizeof(int));
Marshal.FreeCoTaskMem(lpBuffer);
}
}
请查看以下内容:
http://social.msdn.microsoft.com/Forums/en/wpf/thread/860d1b66-23c2-4a64-875b-1cac869a5e5d
private static void _DeleteSingleCookie(string name, Uri url)
{
try
{
// Calculate "one day ago"
DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
// Format the cookie as seen on FB.com. Path and domain name are important factors here.
string cookie = String.Format("{0}=; expires={1}; path=/; domain=.facebook.com", name, expiration.ToString("R"));
// Set a single value from this cookie (doesnt work if you try to do all at once, for some reason)
Application.SetCookie(url, cookie);
}
catch (Exception exc)
{
Assert.Fail(exc + " seen deleting a cookie. If this is reasonable, add it to the list.");
}
}
我没有测试过,但我认为最好的方法是在页面上定义一个Javascript方法(如果你能够的话),用于清除Cookie。
document.cookie='c_user=;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=.facebook.com';
(或者使用其他的cookie名称)。然后,您可以在WebBrowser控件上使用InvokeScript方法。