asp.net - 如何在 ASP.NET 运行时更改 FormsCookieName

标签 asp.net cookies forms-authentication

我们希望根据应用程序实例更改 FormsCookiePath 的 FormsCookieName。我们有一个应用程序,在 1 个服务器/域名上有多个实例。因此,我们只能同时在 1 个应用程序中工作,因为 cookie 会互相覆盖。顺便说一句, session 也是如此。

有没有办法动态地(例如在 Global.asax Application_Start 中)更改此名称?这很有用,因为我们在每个应用程序中保留一个许可证名称,可以用作 CookieName 的基础。

我们已经使用 Web.config 和额外文件来覆盖外部文件中的 Web.config 值,使用:<appSettings file="Web.AppSettings.Config">

但这需要手动操作,这些操作可能会被忘记并且是多余的,因为可以从数据库中检索设置。

谢谢。

最佳答案

我也遇到过类似的情况,我做了以下操作。在 Application_Start 中,我检查了我的 cookie 名称是否需要更改。在对所有应用程序进行新部署(其中所有应用程序都具有相同的 web.config)后,就会发生这种情况。


protected void Application_Start(object sender, EventArgs e)
{
  // determine unique cookie name per application
  string cookieName = ...
  // Get the web.config forms settings
  Configuration c = WebConfigurationManager.OpenWebConfiguration("~");
  AuthenticationSection auth = c.GetSection("system.web/authentication") 
        as AuthenticationSection;
  // See if we have mismatch in web.config or in Forms cookiename
  if (auth != null && auth.Forms != null && 
       (auth.Forms.Name != cookieName 
          || FormsAuthentication.FormsCookieName != cookieName
       )
     )
  {
     // Assign value in web.config for future restarts
     auth.Forms.Name = cookieName;
     // would be nice if this restarted the app, but it doesn't appear to
     c.Save();
     // This seems to restart the app
     System.Web.HttpRuntime.UnloadAppDomain();
  }
  ...
}

web.config 在应用程序启动时修改,然后重新启动 Web 应用程序。下次启动网络应用程序时,Cookie 名称会同步,并且会跳过重置代码。

关于asp.net - 如何在 ASP.NET 运行时更改 FormsCookieName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/264813/

相关文章:

javascript - 当用户转到不同的页面时,如何保持 div 可见?

c# - 显示最近查看的项目

c# - 使用 FormsAuthentication.SetAuthCookie 存储更多信息

c# - ViewBag 属性已设置但不可访问

c# - 来自 Active Directory 的间歇性未知错误

javascript - xhr.withCredentials = true;不适用于 Chrome

c# - Membership.ValidateUser() 的目的是什么

c# - OnAuthorization 中的 MVC 重定向导致授权失败

asp.net - 把网站改成https?

c# - ASP.net ListView 在 ItemUpdating 事件中访问控件