会话到期时返回登录操作

时间:2017-04-12 10:37:51

标签: asp.net-mvc-4

我想要在会话到期时将我的页面重定向到登录页面这是我的代码,我不知道它有什么问题,但是它不起作用,有人可以帮忙吗?

public class SessionExpireAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    HttpContext ctx = HttpContext.Current;
    // check  sessions here
    if (HttpContext.Current.Session["username"] == null)
    {
        filterContext.Result = new RedirectResult("~/Account/Login");
        return;
    }
    base.OnActionExecuting(filterContext);
}
}

namespace FinalTimesheetProject.Controllers
{
public class BaseController : Controller
{
    static string startdate,enddate;

    //
    // GET: /Base/

    [SessionExpire]
    public ActionResult Index()
    {
        return View();
    }

1 个答案:

答案 0 :(得分:0)

Heyaa,我已经解决了它,实际上我之前发布的代码不适用于ajax发布请求..所以我为它写了不同的条件,现在它的工作..谢谢..并编写此代码进入你的控制器因为类redirectToAction方法不起作用

代码:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["username"] == null)
        {
            //CHECK REQUSET TYPE = GET
            if (Request.RequestType.Equals("GET"))
            {
                //IF REQUEST IS AJAX
                if (Request.IsAjaxRequest())
                {
                    filterContext.Result = Json("SESSION_KILLED", JsonRequestBehavior.AllowGet);
                    return;
                }
                //NORMAL REQUSET
                else
                {
                    filterContext.Result = RedirectToAction("Login","Account");
                    return;
                }
            }
            //REQUEST TYPE IS POST
            else
            {
                filterContext.Result = Json("SESSION_KILLED", JsonRequestBehavior.AllowGet);
                return;
            }
        }
        base.OnActionExecuting(filterContext);
    }