0

Scenerio - 我正在编写一个基于您使用的登录框(database1 和 database2)的 Web 应用程序,它将您连接到相应的数据库。我已将 web.config 设置为保存两个连接字符串。在每个框的 On_Authenticate 方法上,我检查以验证用户身份,然后将基于登录框的字符串发送到名为 Authenticate user 的类中的公共变量。此公共变量检查 cookie 并从变量中获取连接字符串名称,如果 cookie 为空,它会设置一个新 cookie,使所有现有 cookie 过期并设置 cookie 值。

现在一旦完成,每次我访问数据库(使用 LINQ2SQL)时,我都会创建一个数据上下文并发送 AuthenticatedUser.ConnectionString。这将检查 cookie 并发送获取用于提取数据的连接字符串。Herer 是 AuthenticatedUser 类...

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.Request.Cookies.Add(cookie);
    }
}

private static string GetConnectionStringFromName(HttpCookie myCookie)
{
    string connectionStringName = myCookie.Value;
    return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}

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/ 但是在我使用的第一个真正的数据库调用中,我PortalDataContext db = new PortalDataContext(AuthenticatedUser.ConnectionString); 得到一个空引用错误。它正在通过 Get 并检查 cookie 并返回一个空 cookie。这里会发生什么?

4

1 回答 1

1

设置时需要将 cookie 添加到 Reponse.Cookies 集合而不是 Request.Cookies 集合。只有响应中的 cookie 被发送回用户的浏览器。

于 2010-09-29T13:43:13.553 回答