Arumuga Nainar P
Arumuga Nainar P

Reputation: 11

MVC : How to clear session and close the current browser tab on click of logout link?

I am trying to clear the session and the close the browser tab on logout link click. Please help me to do this.

Thanks in advance

Upvotes: 0

Views: 11614

Answers (4)

Vishnoo Rath
Vishnoo Rath

Reputation: 580

This code is from MSDN. I have added the async : false to the jQuery call as that is the key to ensure that the call flushes the Server Side session and then the window closes.

<script type="text/javascript"> 
      
	$(document).ready(function () { 
		window.addEventListener('beforeunload',recordeCloseTime); 
	}); 
    
	function recordeCloseTime() { 
 
    	$.ajax({ 
    		type: "POST", 
            async: false,
        	url: "ServiceToClearSession.asmx/RecordCloseTime", 
		});      
	} 

</script> 

Upvotes: 0

Dharmesh S. Patil
Dharmesh S. Patil

Reputation: 21

You can send an ajax request to to an action method which clears the session variables and in the call back, you can close the window.

<a id=logoutLink">Logout</a>

<script type="text/javascript">

$(function(){

  $("#logoutLink").click(function(e){
   e.preventDefault();
   $.post("@Url.Action("Logout","User")",function(res){
      if(res.status==="done")
      {
         //close the window now.
         window.close();
      }
   });
  });

});
</script>

Now in your UserController, Add the Logout action method

public class UserController : Controller
{
   [HttpPost]
   public ActionResult Logout()
   {
      Session.Abandon();
      return Json(new { status="done"});
   }
}

Reference: MVC for clossing browser tab when logout

Upvotes: 0

chenZ
chenZ

Reputation: 930

Session.Abandon();
or
Session.Clean();
or
Session[".."]=null;

close windows you can use js

windows.close();

in some browser,it will pop a confirm

Upvotes: 0

koenmetsu
koenmetsu

Reputation: 1034

You're trying to achieve two different things, one of which is a server-side concern, the other a client-side concern.

You could try splitting up these concerns, for example:

A: Using some Post/Redirect/Get laced with tab-closing javascript

  1. Post to Logout controller method
  2. Redirect to /LogoutSuccess
  3. Put some javascript that closes the browser tab on body load, in the LogoutSuccess view.

B: A more client-side approach

  1. Perform (in your javascript) a http GET to /Logout
  2. Upon 200 OK response, execute some javascript that closes the browser tab.

Upvotes: 0

Related Questions