如何终止会话或会话ID(ASP.NET/C#)

30 c# asp.net session webmatrix razor

当用户单击注销按钮时,如何销毁会话(Session ["Name"])?

我正在浏览MSDN上的ASP.NET API参考,它似乎没有太多信息.看起来相当有限.但我找不到ASP.NET类等的任何其他页面.

我试过了:

Session.Abandon();Session.Contents.Remove("Name");他们都没有工作.(我在谷歌搜索的论坛中发现了这些)

Kel*_*sey 61

Abandon方法应该工作(MSDN):

Session.Abandon();
Run Code Online (Sandbox Code Playgroud)

如果要从会话使用中删除特定项目(MSDN):

Session.Remove("YourItem");
Run Code Online (Sandbox Code Playgroud)

编辑:如果您只想清除值,您可以执行以下操作:

Session["YourItem"] = null;
Run Code Online (Sandbox Code Playgroud)

如果要清除所有键,请执行以下操作:

Session.Clear();
Run Code Online (Sandbox Code Playgroud)

如果这些都不适合你,那么就会发生一些可疑的事情.我会检查您分配值的位置,并确认在清除值后没有重新分配.

简单检查一下:

Session["YourKey"] = "Test";  // creates the key
Session.Remove("YourKey");    // removes the key
bool gone = (Session["YourKey"] == null);   // tests that the remove worked
Run Code Online (Sandbox Code Playgroud)


小智 8

指示客户端浏览器清除会话ID cookie值也是一个好主意.

Session.Clear();
Session.Abandon();
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-10);
Run Code Online (Sandbox Code Playgroud)


Bob*_*Bob 5

Session.Abandon()

这会将会话标记为已放弃,但会话实际上不会在此时被放弃,请求必须先完成.