C# 如何清除 System.Windows.Forms.WebBrowser 会话数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/434469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear System.Windows.Forms.WebBrowser session data?
提问by user54045
How can I clear current session data (cookies, cached data, auth sessions, etc) without restarting the application?
如何在不重新启动应用程序的情况下清除当前会话数据(cookie、缓存数据、身份验证会话等)?
Update: I'm talking about WebBrowser control in Windows.Forms, not the ASP.Net session.
更新:我说的是 Windows.Forms 中的 WebBrowser 控件,而不是 ASP.Net 会话。
回答by Ilya Tchivilev
You have to realise that the way "session state" is tracked, from the point of view of a web server, is by giving the client browser a cookie with a session-id in it. When the browser posts back to the server, that cookie allows the server to associate the request with a stored session state.
您必须意识到,从 Web 服务器的角度来看,跟踪“会话状态”的方式是向客户端浏览器提供一个带有会话 ID 的 cookie。当浏览器回发到服务器时,该 cookie 允许服务器将请求与存储的会话状态相关联。
So the solution is to clear the cookies of the webBrowser control. Eg webBrowser1.Document.Cookies = "", that should work I think.
所以解决办法就是清除webBrowser控件的cookies。例如 webBrowser1.Document.Cookies = "",我认为应该可以。
ASP.NET also has what it calls "cookieless sessions", which work by adding the session id to the url. So if that's the mechanism used by the server, you could try to filter that out of the url. But you won't see that much, it's mostly the cookie based session state.
ASP.NET 也有它所谓的“无cookie 会话”,它通过将会话ID 添加到url 来工作。因此,如果这是服务器使用的机制,您可以尝试将其从 url 中过滤掉。但是你不会看到那么多,它主要是基于 cookie 的会话状态。
回答by Ilya Tchivilev
webBrowser1.Document.Cookies = "" won't work. This call will not clear the cookie. webBrowser1.Document.Cookies = just works as document.cookie in javascript. You should find the cookie you want to clear, sa 'Session', use webBrowser1.Document.Cookies = "Session = ''"; It will just set the cookie to '', as you want.
webBrowser1.Document.Cookies = "" 不起作用。此调用不会清除 cookie。webBrowser1.Document.Cookies = 只是在 javascript 中作为 document.cookie 工作。你应该找到你想要清除的cookie,sa 'Session',使用webBrowser1.Document.Cookies = "Session = ''"; 它只会根据需要将 cookie 设置为 ''。
回答by Jordan Milne
If you have javascript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on (I haven't yet found a way to clear session cookies other than this).
如果您启用了 javascript,您只需使用此代码片段来清除 Web 浏览器当前所在站点的 cookie(除此之外,我还没有找到清除会话 cookie 的方法)。
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
It's derived from this bookmarkletfor clearing cookies.
In addition to this, you can delete the contents of the "C:\Documents and Settings\username\Cookies" folder (minus the index.dat, which is usually locked).
除此之外,您可以删除“C:\Documents and Settings\username\Cookies”文件夹中的内容(减去通常被锁定的 index.dat)。
As for the cached data, it should be sufficient to just delete all of the files in "C:\Documents and Settings\username\Local Settings\Temporary Internet Files".
至于缓存数据,只要删除“C:\Documents and Settings\username\Local Settings\Temporary Internet Files”中的所有文件就足够了。
If you reallyneed to be able to clear the cookies for all sites, you're probably better off using something like the axWebBrowser control in the long run.
如果您真的需要能够清除所有站点的 cookie,从长远来看,您最好使用 axWebBrowser 控件之类的东西。
回答by Jordan Milne
To clear session (such as HttpOnly cookies), you can use InternetSetOption() from wininet.dll.
要清除会话(例如 HttpOnly cookie),您可以使用 wininet.dll 中的 InternetSetOption()。
private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
and use this method whenever need to clear session.
并在需要清除会话时使用此方法。
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);
webBrowser1.Document.Window.Navigate(url);
回答by Travis
I tried everything to clear the form data so the next user would not see the previous email address, etc. I ended up doing this to clear the cookies...
我想尽一切办法清除表单数据,这样下一个用户就看不到以前的电子邮件地址等。我最终这样做是为了清除 cookie...
string[] theCookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
foreach (string currentFile in theCookies)
{
try
{
System.IO.File.Delete(currentFile);
}
catch (Exception ex)
{
}
}
回答by Passing
Windows 7 uses index.dat files to store cookies and history so that Bill and his freinds at CIA central can snoop on you and have done all they can to ensure you can not delete these files and that after taking copies because 'Special Folders' are used and the .Dat files remain locked whilst windows is running.
Windows 7 使用 index.dat 文件来存储 cookie 和历史记录,以便 Bill 和他在 CIA 中心的朋友可以窥探您并已尽其所能确保您无法删除这些文件,并且在复制后,因为“特殊文件夹”是使用并且 .Dat 文件在 Windows 运行时保持锁定状态。
This is not a perfect solution but it works to some degree with the full file names being in a List.
这不是一个完美的解决方案,但它在某种程度上适用于列表中的完整文件名。
int DeletedCount = 0;
int CouldNotDelete = 0;
KillExplorer();
foreach (string DatFile in DatFiles)
{//Do not put break point or step into the code else explorer will start and the file will become locked again
DirectoryInfo DInfo=new DirectoryInfo(DatFile.Replace("index.dat",""));
FileAttributes OldDirAttrib = DInfo.Attributes;
DInfo.Attributes = FileAttributes.Normal;//Set to normal else can not delete
FileInfo FInfo = new FileInfo(DatFile);
FileAttributes OldFileAttrib = FInfo.Attributes;
SetAttr(FInfo, FileAttributes.Normal);
TryDelete(FInfo);
SetAttr(FInfo, OldFileAttrib);//Sets back to Hidden,system,directory,notcontentindexed
if (File.Exists(DatFile))
CouldNotDelete++;
else
DeletedCount++;
}
if (DatFiles.Count>0)//Lets get explorer running again
System.Diagnostics.Process.Start(DatFiles[DatFiles.Count - 1].Replace("index.dat", ""));
else
System.Diagnostics.Process.Start("explorer");
System.Windows.Forms.MessageBox.Show("Deleted " + DeletedCount + " Index.dat files with " + CouldNotDelete + " Errors");
return "Deleted " + DeleteFileCount + " Files ";
}
private void KillExplorer()
{
foreach (Process P in Process.GetProcesses())
{//Kill both these process because these are the ones locking the files
if (P.ProcessName.ToLower() == "explorer")
P.Kill();
if (P.ProcessName.ToLower() == "iexplore")
P.Kill();
}
}
private bool TryDelete(FileInfo Info)
{
try
{
Info.Delete();
return true;
}
catch
{return false;}
}
private void SetAttr(FileInfo Info,FileAttributes Attr)
{
try
{
Info.Attributes = Attr;
}
catch { }
}
回答by Advait Purohit
Following solution worked for me -
以下解决方案对我有用 -
webBrowser1.Document.ExecCommand("ClearAuthenticationCache", false, null);
This was suggested in following post for deleting cookies - https://stackoverflow.com/a/21512662/6291511
这是在以下删除 cookie 的帖子中建议的 - https://stackoverflow.com/a/21512662/6291511
You can find more info regarding this here - https://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.execcommand(v=vs.110).aspx
您可以在此处找到有关此的更多信息 - https://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.execcommand(v=vs.110).aspx
Hope it helps!!!
希望能帮助到你!!!
回答by KleberBH
Private Const INTERNET_OPTION_END_BROWSER_SESSION As Integer = 42
<DllImport("wininet.dll", SetLastError:=True)>
Public Shared Function InternetSetOption(hInternet As IntPtr, dwOption As Integer, lpBuffer As IntPtr, lpdwBufferLength As Integer) As Boolean
End Function
Private Sub WebBrowserFormName_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0)
End Sub
Just posting for someone looking for this answer in VB. Happy coding!!!
只是为在 VB 中寻找这个答案的人发帖。快乐编码!!!