在 WPF Web 浏览器控件中删除 Cookie

3

我正在开发一个基于WPF的应用程序,其中涉及到与Twitter API的交互。为了展示Twitter认证页面,我使用了WPF Web-Browser控件。我能够成功地登录并使用Twitter API。但是我的问题是,我需要清除Web浏览器的cookies以实现注销功能。有没有办法在WPF Web-Browser中清除会话cookie?

3个回答

6
我昨天遇到了这个问题,今天终于想出了完整的解决方案。答案在这里提到,更详细的介绍在这里这里
主要问题是,在WPF和WinForms中,WebBrowser不允许您修改(删除)现有的会话cookie。这些会话cookie可以防止多用户单设备体验成功。
上面链接中的StackOverflow回应省略了一个重要部分,它需要使用不安全的代码块,而不是使用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);
    }
}

2

请查看以下内容:

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.");
        }
    }

Ponmalar,感谢您的回复。我已经尝试过那个链接,但对我没有用。我相信那里描述的方法只清除了持久性cookie而不是会话cookie。我需要清除会话cookie。也许这样可以澄清问题。 - user786981
你有没有查看过https://dev59.com/lXNA5IYBdhLWcg3wjOve? - Ponmalar

0

我没有测试过,但我认为最好的方法是在页面上定义一个Javascript方法(如果你能够的话),用于清除Cookie。

document.cookie='c_user=;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=.facebook.com';

(或者使用其他的cookie名称)。然后,您可以在WebBrowser控件上使用InvokeScript方法。


dbaseman,感谢您的回复。我正在使用Twitter API访问Twitter,因此我不认为我可以在该页面上定义JavaScript方法,或者我是否误解了什么?如果我是正确的,那么还有其他方法可以做到吗? - user786981

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接