会话和表单身份验证问题:Asp.Net MVC 3

时间:2011-01-30 17:05:09

标签: asp.net asp.net-mvc session asp.net-mvc-3

当我在开发Asp.Net MVC 3应用程序时,我在我的应用程序中使用了FormAuthentication

问题是,在登录系统后,当我关闭浏览器(没有注销)并再次在浏览器中打开页面(比如说/Admin/ProductList/)时,page is still being invokedI got focus in my controller too 。 [这真的很糟糕! :(]

我想要的是,当我关闭浏览器并在任何页面上再次返回时,它应该转到logged in page

查看给定代码以便您理解。

public void SignIn(string userName, bool isCookiePersistent)
        {

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddDays(14),
                createPersistentCookie, string.Empty);

            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, isCookiePersistent);
            if (authTicket.IsPersistent)
            {
                authCookie.Expires = authTicket.Expiration;
            }

            authCookie.Value = FormsAuthentication.Encrypt(authTicket);
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }

public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

Web.Config代码:

<authentication mode="Forms">
      <forms loginUrl="~/Admin/Login" timeout="2880" />
    </authentication>

My page is getting in **Redirection Loop**: This is the main issue.

我错过了any other settings or global.asax event handling吗?

请给我任何解决方案来帮助我。

提前致谢。

1 个答案:

答案 0 :(得分:3)

下面:

authCookie.Expires = authTicket.Expiration;

这就是使身份验证cookie持久化并且浏览器将其存储在客户端计算机上的原因,这样当您重新启动浏览器时,cookie仍然存在。如果您不想要持久性cookie,可以试试这个:

public void SignIn(string userName)
{
    var authTicket = new FormsAuthenticationTicket(
        1, userName, DateTime.Now, DateTime.Now.AddDays(14), false, string.Empty
    );
    var authCookie = FormsAuthentication.GetAuthCookie(userName, false);
    authCookie.Value = FormsAuthentication.Encrypt(authTicket);
    HttpContext.Current.Response.Cookies.Add(authCookie);
}