DataTables ASP.Net timeout issue

1.3k Views Asked by At

We are using datatables with ASP.Net MVC and identity framework. I have set the authentication timeout to 1 minute using the code below:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        ...

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            ExpireTimeSpan = System.TimeSpan.FromMinutes(1),
            Provider = new CookieAuthenticationProvider
            {
                ...
        });

I then login and go to a page with a datatable and wait for the timeout. An error occurs if the timeout expires and the datatable tries to hit the server. The datatable works by making an ajax request to the server and this is where the error comes from.

The error is a JavaScript error:

DataTables warning: table id=DataTables_Table_0 - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

I need to handle this gracefully and redirect the user to the login page.

Can anyone help please?

2

There are 2 best solutions below

1
On

.NET has a built in Time Out Exception:

try 
    {
        // your logic here that might time out
    }
catch (TimeoutException e)
    {
       // your logic here if it does time out
    }

More: https://msdn.microsoft.com/en-us/library/system.timeoutexception(v=vs.110).aspx

EDIT:

For an AJAX time out, maybe this thread would help?

Handling session timeout in ajax calls

10
On

You can always use the Application_Error event handler in the Global.asax file. Add the:

protected void Application_Error(object sender, EventArgs e)
{
    //Redirect code here
}

method, and load in your code to check if the login is valid. If not, you can route them to another page. In one of my projects a while back I used the RouteData class to send them to another page:

//send to the error page
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");

if (!userAuthorized)
    routeData.Values.Add("action", "NotAuthorized");
else
    routeData.Values.Add("action", "Index");

routeData.Values.Add("message", exception.Message);

IController errorController = new DevWebApp.Controllers.ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));