I was looking to improve my page authentication handling in asp.net MVC, so I was reading this guide (http://markfreedman.com/index.php/2012/02/28/handling-session-and-authentication-timeouts-in-asp-net-mvc/) and I tried his example:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// If the browser session or authentication session has expired...
if (ctx.Session["UserName"] == null || !filterContext.HttpContext.Request.IsAuthenticated)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// For AJAX requests, we're overriding the returned JSON result with a simple string,
// indicating to the calling JavaScript code that a redirect should be performed.
filterContext.Result = new JsonResult { Data = "_Logon_" };
}
else
{
// For round-trip posts, we're forcing a redirect to Home/TimeoutRedirect/, which
// simply displays a temporary 5 second notification that they have timed out, and
// will, in turn, redirect to the logon page.
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "Index" }
});
}
}
base.OnActionExecuting(filterContext);
}
}
But I noticed that many of my links are Ajax.ActionLinks like this:
<ul>@Ajax.ActionLink("Employees", "Index", "Employee", new AjaxOptions { UpdateTargetId = "employee_detail" })</ul>
When I do this, the login view is correctly returned after the authentication expires, but returned inside the page div instead of reloading the entire page. Is it possible to set that in a view? To say “if I’m inside a div, just reload the whole page?”
Thanks.
Judging by the documentation of Ajax.ActionLink, it looks like OnFailure will be called if a non-200 status code is returned. In your attribute, be sure to add a status code, something similar to:
Once that’s in there, the OnFailure script name can be added to your ActionLink: