2012-05-30 65 views
2

我正在開發一個WPF應用程序,我正在使用twitter API。要顯示Twitter認證頁面,我正在使用WPF Web瀏覽器控件。我能夠成功登錄並使用twitter API。我的問題是,我需要清除Web瀏覽器的Cookie來實現註銷功能。有沒有什麼方法可以清除WPF Web瀏覽器中的會話cookie?刪除WPF Web瀏覽器控件中的cookie

回答

3

檢查以下,

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

Ponmalar,謝謝你的回覆。我已經嘗試了這個鏈接,但是這對我沒有幫助。我相信那裏描述的方法會清除持久cookie而不是會話cookie。我需要清除會話cookie。可能會說明問題。 –

+0

你檢查過http://stackoverflow.com/questions/912741/c-webbrowser-control-how-to-delete-cookies-from-windows-form – Ponmalar

0

我還沒有測試過這個,但我認爲最好的方法是在頁面上定義一個Javascript方法(如果可以的話)來清除cookie。

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

(或任何cookie名稱)。然後您可以使用InvokeScript方法對WebBrowser進行控制。

+0

dbaseman,感謝您的回覆,我使用Twitter的API來訪問Twitter,所以我不認爲我可以在頁面上定義一個JavaScript方法,還是我誤解的東西嗎?如果我是對的,那麼還有其他方法可以做到嗎? –

3

我昨天就遇到了這個問題,今天終於想出了一個完整的解決方案。答案提到here這是更詳細的herehere

這裏的主要問題是WebBrowser(在WPF和WinForms中)不允許您修改(刪除)現有會話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); 
    } 
}