2010-10-07 88 views
1

我有一个代码库的Web应用程序连接到2个数据库。根据用户使用哪个登录控件进行登录,将不同的数据库连接到代码。我正在做一个cookie的所有这一切。该cookie位于名为AuthenticatedUser的公共类中。这个类看起来是这样的:强制.net登录控制,使用户注销,如果cookie为空

public class AuthenticatedUser : System.Web.UI.Page 
{ 
    public static string ConnectionString 
    { 
     get 
     { 
      HttpCookie myCookie = HttpContext.Current.Request.Cookies["connectionString"]; 
      return GetConnectionStringFromName(myCookie); 
     } 
     set 
     { 
      if (HttpContext.Current.Request.Cookies["connectionString"] != null) 
      { 
       ExpireCookies(HttpContext.Current); 
      } 
      var allCookies = HttpContext.Current.Request.Cookies.AllKeys; 
      HttpCookie cookie = new HttpCookie("connectionString"); 
      cookie.Value = value; 
      cookie.Expires = DateTime.Now.AddYears(100); 
      HttpContext.Current.Response.Cookies.Add(cookie); 
     } 
    } 

    private static string GetConnectionStringFromName(HttpCookie myCookie) 
{ 
    try 
    { 
     string connectionStringName = myCookie.Value; 
     return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; 
    } 
    catch 
    { 
     FormsAuthentication.SignOut(); 
    } 
    finally 
    { 
     HttpContext.Current.Response.Redirect("/default.aspx"); 
    } 
    return ""; 

}  private static void ExpireCookies(HttpContext current) 
    { 
     var allCookies = current.Request.Cookies.AllKeys; 
     foreach (var cook in allCookies.Select(c => current.Response.Cookies[c]).Where(cook => cook != null)) 
     { 
      cook.Value = ""; 
      cook.Expires = DateTime.Now.AddDays(-1); 
      current.Request.Cookies.Remove(cook.Name); 
      cook.Name = ""; 
     } 
    } 
} 

这似乎是工作我的机器上,但是当我试图部署它,这是使用网站上的“记住我”选项的用户是越来越空引用错误,因为他们没有使用登录控件来获取cookie。

解决此问题的最佳方法是什么?我想如果一个用户登录,但AuthenticatedUser类无法获得一个Connectionstring注销用户强制他们再次使用登录控制。我该怎么办?

回答

1

尝试使用:

try 
{ 
     FormsAuthentication.SignOut(); 
} 
finally 
{ 
     Response.Redirect("~/Home.aspx"); 
} 

这种方式是最好的,例如如果在某些时候你会决定一事─cookie认证,但基于URL - 在FormsAuthentication会优雅地管理它。

+0

我已经更新了代码,那是你在想什么?我试图在我的开发机器上测试它,但我很难再次解决这个问题。这种结构是否正确? – EvanGWatkins 2010-10-07 13:35:45

+0

@EvanGWatkins - 实际上FormsAuthentication.SignOut()会清除身份验证cookie(如果通过ASP.Net标准方式验证,或者至少通过FormsAuthentication.SetAuthCookie验证)。所以你不需要手动删除它。 – Dewfy 2010-10-07 14:23:39

+0

你能解释一下吗?成员登录是标准登录,所以我需要做的就是检查cookie(在尝试中),如果它很棒,继续移动,如果它为空,则注销用户并将其重定向到登录名。 – EvanGWatkins 2010-10-07 14:26:03