使用ASP.NET MVC会话到期时重定向到登录页面

Man*_*lly 14 ajax asp.net-mvc

我正在使用ASP.NET MVC.我想在会话到期时重定向到登录页面.我怎样才能做到这一点?如果我正在对控制器中的方法进行AJAX调用,那么如果我的会话在那种情况下到期,我也想重定向到登录页面.

Fel*_*ani 14

你可以通过3种方式做到这一点:

  1. 为您的操作创建一个过滤器并应用它在OnActionExecuting中编写代码(在执行操作之前),http://www.asp.net/mvc/tutorials/understanding-action-filters-cs

  2. 创建一个基类(继承自Controller类)并使控制器继承自此类.在这个类中,您可以覆盖一个名为OnActionExecuting的方法,就像过滤器一样.

  3. 不要使用Session进行身份验证,您可以使用Forms身份验证并使其易于使用,请查看:http://weblogs.asp.net/fredriknormen/archive/2008/02/07/asp-net-mvc-framework -使用表单,authentication.aspx

在我看来,解决方案3比其他解决方案更好.我希望这个对你有用!

  • 解决方案3是错误的.使用表单身份验证,用户仍然可以通过cookie进行身份验证,但具有全新的会话.如果您的控制器没有捕获到这个,那么您可以尝试访问尚未由登录页面配置的Session对象. (6认同)

Mic*_*ael 7

因为可以复制Forms-Authentication的security-cookie使用它来模拟注册用户我使用以下属性将身份验证绑定到当前会话生存期.

要使属性工作,您必须在登录时设置session ["user"] = MyUser并在注销时调用session.abandom().我不知道重定向是否适用于ajax调用 - 这是你必须尝试的.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CheckUserSessionAttribute : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpSessionStateBase session = filterContext.HttpContext.Session;
        var user = session["User"];

        if (((user == null) && (!session.IsNewSession)) || (session.IsNewSession))
        {
            //send them off to the login page
            var url = new UrlHelper(filterContext.RequestContext);
            var loginUrl = url.Content("~/Account/LogOff");
            session.RemoveAll();
            session.Clear();
            session.Abandon();
            filterContext.HttpContext.Response.Redirect(loginUrl, true);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)