Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Logout User After Browser Close in ASP.NET C# Using Web Services

4.10/5 (5 votes)
20 Jun 2015CPOL2 min read 34.1K   538  
Logout User After Browser Close in ASP.NET C# Using Web Services

Introduction

Keeping track of user's time in your web application is one of the most important issues to maintain. It not only helps to keep track of users but also helps to solve any other analytical problems with application's data, like average in time, average out time, average time spent in your application, etc. So how to keep the users login logout information of your web application.

By clicking on the login button, you can easily get the login time, and I hope you have kept your session checking active during logging of your users. On the other hand, by clicking on the Logout button, you can also trace the logout time. But what happens when user closes the browser, then how will you keep track of user's logout time. Here in this post, we will discuss about this serious issue.

Using of Web Services

Instead of using normal methods, we will use Web services to get the logout time for the user.

What is Web Services?

According to MSDN

Web services are components on a Web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web services or to use built-in application services, and to call these services from any client application.

Key Concept

There is a function named onbeforeunload of JavaScript. This is called at the time of unloading the web page, whether you are closing the browser or closing the tab or redirecting to any other web page from that particular page, where it is coded. Do not use an alert() within onbeforeunload, it will not work.

Using this, we are getting the login session id and pass it to the web services. And in web service, we are doing our necessary thing (SQL server entry or putting it in any Notepad with login id, etc.).

Using the Code

Let's create a project and name it whatever you want. Add a new web form and design it according to your needs.

On the aspx page's head section, write down the following code:

XML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
window.onbeforeunload = function (evt) {
    var message = 'You have started writing or editing a post.';
	var loginId = '<%= Session["LoginId"].ToString() %>';
	console.log('in');
				 
	$.ajax({
	    url: "Logout.asmx/LogoutMethod",
		contentType: "application/json; charset=utf-8",
		type: "POST",
		success: function (data) {
		    alert(data);
		},
		error: function (x, y, z) {
		    alert(x.responseText + "  " + x.status);
		}
    });
}
</script>

On body, you do whatever your design or work. In the web services, write down again the following code. And make sure that [System.Web.Script.Services.ScriptService] is uncommented.

C#
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 

[System.Web.Script.Services.ScriptService]
public class Logout : System.Web.Services.WebService
{
    [WebMethod (EnableSession = true)]
	public string LogoutMethod()
	{
        // take a log.txt and write on there with time
		string a = Session["LoginId"].ToString();
		File.AppendAllText(Server.MapPath("~/log.txt"),
                "Login id loges out "+a+ " at "+ DateTime.Now.ToString()+ Environment.NewLine);

        return "";
	}
}

Before running this, create a log.txt file in your solution explorer, where all your logout log will be stored.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)