Hi I am developer in .NET but I need to access session object in client side and redirect the page to login. i am using the following code snippet but I am unable to achieve the target.

function CheckSession() {
                var session = '<%=Session["username"] != null%>';
                //session = '<%=Session["username"]%>';
                if (session == false) {
                    alert("Your Session has expired");
                    window.location = "login.aspx";
                else {

I am getting

'<%=Session["username"] != null%>'

this condition as always true whether the session has expired or not.

Is there any way to check that the session has expired or not.

Any help will be appreciated.

You want to use the following...

var session = <%=Session["username"] != null ? "true" : "false"%>;

Now for as to why you would want to do this is beyond me? If you can check this when the page is being processed on the server you can simply force a redirect like the following...

if(Session["username"] == null) {
    Response.Redirect("login.aspx", true);

But i'm assuming this is also not what your after. If you want to check the users session is valid repeatedly e.g every 30 seconds then neither of those methods will work.

The reason being is that once the server has sent the page to the user the session check is calculated and hard-coded into the JavaScript. It will NOT be re-assessed everytime you call the javascript method as it is static.

To perform this you will need two steps, the first is to setup a page to return a flag indicating whether a users session is valid and secondly perform an asynchronous request to fetch the users session state.

First of all create a page e.g. SessionCheck.aspx and add the following...

{"valid":<%=Session["username"] != null ? "true" : "false" %>}

Secondly add the following script to your existing page...

function checkSession() {
    var request = false;

    if(window.XMLHttpRequest) { // Mozilla/Safari
        request = new XMLHttpRequest();
    } else if(window.ActiveXObject) { // IE
        request = new ActiveXObject("Microsoft.XMLHTTP");
    request.open('POST', 'SessionCheck.aspx', true);
    request.onreadystatechange = function() {
        if(request.readyState == 4) {
            var session = eval('(' + request.responseText + ')');
            if(session.valid) {
            } else {
                alert("Your Session has expired");
                window.location = "login.aspx";

The above snippets will make a request to the SessionCheck.aspx page, which in turn returns a small parcel of JSON which once the script receives this, evals it into a javascript object so we can access the flag 'valid' which will be true or false depending on whether the user is logged in.

Hope it helps.

Thanks but this is more than I asked. Anyway I got my answer. This solution will definitely help me in future.