2017-04-05 39 views
3

如何删除特定网站或网页的身份验证Cookie?目前,如果我通过WPF WebBrowser使用OAuth 2.0登录,我的登录会话被保存,但每次关闭我的应用程序时我都要重置会话。如何清除特定网站的WPF WebBrowser中的cookie?

public partial class VKLogin : Window 
    { 
     public string AccessToken { get; set; } 

     public VKLogin() 
     { 
      InitializeComponent(); 

      this.Loaded += (object sender, RoutedEventArgs e) => 
      { 
       webBrowser.Navigate("https://oauth.vk.com/authorize?client_id=5965945&scope=wall&redirect_uri=https://oauth.vk.com/blank.html&display=page&v=5.63&response_type=token"); 
      }; 
     } 

     private void webBrowser_Navigated(object sender, NavigationEventArgs e) 
     { 
      var url = e.Uri.Fragment; 
      if (url.Contains("access_token") && url.Contains("#")) 
      { 
       url = (new System.Text.RegularExpressions.Regex("#")).Replace(url, "?", 1); 
       AccessToken = System.Web.HttpUtility.ParseQueryString(url).Get("access_token"); 
      } 
     } 

     private void Window_Closed(object sender, EventArgs e) 
     { 
      webBrowser.Dispose(); 
     } 
    } 

XAML

<Grid> 
    <WebBrowser Name="webBrowser" 
      Navigated="webBrowser_Navigated" 
      /> 
</Grid> 

回答

3

如果你想删除所有Cookie,您可以使用InternetSetOption function,解释here

的代码将是这样的:

[System.Runtime.InteropServices.DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] 
public static extern bool InternetSetOption(int hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); 

private static unsafe void SuppressWininetBehavior() 
{ 
    /* SOURCE: http://msdn.microsoft.com/en-us/library/windows/desktop/aa385328%28v=vs.85%29.aspx 
     * INTERNET_OPTION_SUPPRESS_BEHAVIOR (81): 
     *  A general purpose option that is used to suppress behaviors on a process-wide basis. 
     *  The lpBuffer parameter of the function must be a pointer to a DWORD containing the specific behavior to suppress. 
     *  This option cannot be queried with InternetQueryOption. 
     *  
     * INTERNET_SUPPRESS_COOKIE_PERSIST (3): 
     *  Suppresses the persistence of cookies, even if the server has specified them as persistent. 
     *  Version: Requires Internet Explorer 8.0 or later. 
     */ 

    int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/; 
    int* optionPtr = &option; 

    bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int)); 
    if (!success) 
    { 
     //Something went wrong 
    } 
} 

,然后使用调用函数InitializeComponent();等之后:

SuppressWininetBehavior(); 

另外,如果你有使用Javascript功能,您可以使用下面的代码:

function delete_cookie(name) { 
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; 
} 
相关问题