Click here to Skip to main content
15,885,984 members
Articles / Web Development / HTML

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

Rate me:
Please Sign up or sign in to vote.
4.10/5 (5 votes)
20 Jun 2015CPOL2 min read 32.9K   535   7   11
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)


Written By
Software Developer PwC
India India
I am a Software developer having an experience of 5 years in application development. To get me you can mail me at arkadeepde@gmail.com or you can visit my blog at ASP With Arka

Comments and Discussions

 
QuestionNot working Pin
Member 1264147320-Dec-16 0:38
Member 1264147320-Dec-16 0:38 
Questiondownload link is not working.. Pin
Sucheta Bhaumik22-Jun-15 7:09
Sucheta Bhaumik22-Jun-15 7:09 
AnswerRe: download link is not working.. Pin
Arkadeep De22-Jun-15 7:10
professionalArkadeep De22-Jun-15 7:10 
GeneralRe: download link is not working.. Pin
Sucheta Bhaumik22-Jun-15 7:12
Sucheta Bhaumik22-Jun-15 7:12 
QuestionNot an article Pin
Akhil Mittal21-Jun-15 22:14
professionalAkhil Mittal21-Jun-15 22:14 
SuggestionRe: Not an article Pin
Jochen Arndt21-Jun-15 22:45
professionalJochen Arndt21-Jun-15 22:45 
GeneralRe: Not an article Pin
Arkadeep De22-Jun-15 1:22
professionalArkadeep De22-Jun-15 1:22 
GeneralNo better solution than any other Pin
Zoltán Zörgő21-Jun-15 1:58
Zoltán Zörgő21-Jun-15 1:58 
This topic has been addressed here on CP so many times. Your suggestion is of use mainly when it is in line with the overall software architecture - it won't be wise to implement such a method in combination with a WebAPI or MVC application for example. Either way, the main issue with all active logout solutions is that you can't trust the client. Such a solution won't be able to react when user kills the browser or when connection is broken for any reason.
GeneralRe: No better solution than any other Pin
Arkadeep De21-Jun-15 6:00
professionalArkadeep De21-Jun-15 6:00 
GeneralRe: No better solution than any other Pin
Thanks787221-Jun-15 20:18
professionalThanks787221-Jun-15 20:18 
GeneralRe: No better solution than any other Pin
Arkadeep De22-Jun-15 1:23
professionalArkadeep De22-Jun-15 1:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.