Handle session timeout in generic http handler
Asked Answered
G

1

6

I have an application where around 20 http generic handler are used for ajax call.
I have used IReadOnlySessionState for accessing the session in my handlers.Everything is working fine.

But when session expires my handler is returning some html as it redirects to default page and html of default page is sent back in the response.

To overcome this issue.
I have checked the session variable in the handler and if it is null the I have written

 context.Response.Write("logout")

And I check in jQuery ajax weather it is logout or anything else.

  $.ajax({
            url: "myhandler.ashx",
            contentType: "application/json; charset=utf-8",
            success: function (data) { checklogout(data); $("#loading").hide(); },
            error: function () { $("#loading").hide(); },
            async: false
         });


If it is logout then I have used location to redirect to login page.
I am using form-authentication to authenticate user.

Is there any better approach for checking and redirecting to login page using jquery-ajax call.

Geometrid answered 25/12, 2012 at 4:21 Comment(1)
It would probably be better to return a proper HTTP status code, such as 401 Unauthorized from your handler (and perhaps create a single base handler so that you don't repeat the logic). You can look for this value in your central AJAX options ($.ajaxsetup), so the code to check only needs to go in one place. Is that along the lines of what you are seeking?Shrum
G
2

You have your handlers in a directory that automatically control by the authentication of asp.net.

What I should do is to not let automatically control by the asp.net authentication by setup that on web.config so the call to the handler will done ether the user is logged in ether not, and inside the handlers I will check for that, if the user that call that handler have the session and the authentication.

Then in the case that the user did not have the authentication to read that handler I return a simple flag to my ajax call, then recognize and make redirect, eg as:

$.ajax({
    url: "myhandler.ashx",
    contentType: "application/json; charset=utf-8",
    success: function (data) 
    { 
        if(data.redirectToLogin == true)
        {
            window.location = "/login.aspx"
        }
        else
        {
            // do the rest job
        }
    },
    error: function () 
    { 
        $("#loading").hide(); 
    }
 });
Granicus answered 30/12, 2012 at 12:32 Comment(2)
Seems to be good idea. But when data has not the property redirectToLogin will it give a java-script exception or not. Also if I use <location path> in my webconfig file will there be any security threat though I will check the user session inside all the handler.Shull
@krshekhar You can simple return a string like "ko" or other flag, this is easy to solve.Granicus

© 2022 - 2024 — McMap. All rights reserved.