I have an requirement to show an alert when user's session has expired and redirect to login page. Actually I have created an Action filter which is applied on a controller and it checks if session is expired , if es it redirects to login page otherwise it lets the action complete successfully.
It is working fine but my problem arises when I make ajax request. For an instance I have ajax.beginform in my view and I have done saving code on that acion method. Now, suppose user has submitted the form when session has expired, before the saving method runs, my actionFilter called up because I have set it at the controller, So, from there it says, redirect to login page. But I am returning Json from controller and it do not redirects.
How should I implement the things?
My code is::::::::::::
For every controller, my Action Filter is defined in same way, I am just going to define only for one controller So, suppose below is my controller.
[CheckSessions]
public class MyController : Controller
{
public ActionResult Add(Model model)
{
Insert code and returns
return Json(new { Msg = Message});
}
}
Action Filter is here
public class CheckSessions: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["LoginSession"] == null && HttpContext.Current.Session["LoginSession"] == null)
{
HttpContext.Current.Response.Redirect("/LoginController/Login");
}
}
}
In View Page:::
@using (Ajax.BeginForm("Add", "MyController ", new AjaxOptions { OnSuccess = "MessageConfirmation" }))
{
Content goes here
}
<script>
Getting Response
function MessageConfirmation(Json) {
alert(Json.StatusCode);
if(Json.StatusCode==404)
{
redirect to login
}
}
</script>
You could not perform the Response.Redirect
for the Ajax request.
Instead redirect you send the response text/code that says the session expires, and redirect using window.location.href
public class CheckSessions: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["LoginSession"] == null &&
HttpContext.Current.Session["LoginSession"] == null)
{
if(HttpContext.Current.Request.IsAjaxRequest())
{
HttpContext.Current.Response.StatusCode="401"; //Session Expired
}
else
{
HttpContext.Current.Response.Redirect("/Account/Login");
}
}
}
}
In Javascript/jQuery check status code ==="401"
OPTION 1:
new AjaxOptions { OnSuccess = "MessageConfirmation(data, status, xhr)" }
function MessageConfirmation(data, status, xhr) {
//check the status code from xhr
window.location.href="/Account/Login";
}
Option 2: do it globally
$.ajax({
statusCode: {
401: function(xhr) {
window.location.href="/Account/Login";
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.