Cookie 支持二级域名和FormsAuthentication 加强版
因为FormsAuthentication验证方式,生成的Cookie的Domain是当前路径中的Domain,并不支持二级域名,所以在
.Text 支持二级域名之二 http://thinhunan.cnblogs.com/archive/2005/10/27/262749.html 一文中,我使用了一种在每处调用SetAuthCookie和SignOut方法时更改写入的Cookie的Domain的方法来使其支持二级域名。
这种方法可行,但有些麻烦。后来又发现更有效更便捷的一种方法,那就是利用HttpModule
public class SecondaryDomainCookieModule : System.Web.IHttpModule
{
public SecondaryDomainCookieModule(){}
public void Dispose(){}
public void Init(System.Web.HttpApplication context)
{
context.EndRequest +=new EventHandler(cookie_Edit_EndRequest);
}
private void cookie_Edit_EndRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
string domain = ".tzl.com";
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie cookie = context.Response.Cookies[cookieName];
if(cookie != null)
{
cookie.Domain = domain;
}
}
}
public class SecondaryDomainCookieModule : System.Web.IHttpModule
{
public SecondaryDomainCookieModule(){}
public void Dispose(){}
public void Init(System.Web.HttpApplication context)
{
context.EndRequest +=new EventHandler(cookie_Edit_EndRequest);
}
private void cookie_Edit_EndRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
string domain = ".tzl.com";
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie cookie = context.Response.Cookies[cookieName];
if(cookie != null)
{
cookie.Domain = domain;
}
}
}