当前位置:编程学习 > C#/ASP.NET >>

如何防止AuthenticateRequest 重复执行

重写 IHttpModule, IPrincipal and IIdentity 实现自定义 Forms验证。 在和Ajax 的Script Manager一同使用的时候,发现  AuthenticateReqeust 会被重复执行N次(至少2次)。如何解决这个问题?

代码 (C#):

 
public sealed class CustomAuthenticationModule : IHttpModule
{
HttpApplication app = null;
const string LOGINURL_KEY = "CustomAuthentication.LoginUrl";
const string AUTHENTICATION_COOKIE_KEY = "CustomAuthentication.Cookie.Name";

/// <summary>
/// Initializes the module derived from IHttpModule when called by the HttpRuntime . 
/// </summary>
/// <param name="httpapp">The HttpApplication module</param>
public void Init(HttpApplication httpapp)
{
this.app = httpapp;
app.AuthenticateRequest += new EventHandler(this.OnAuthenticate);
}

void OnAuthenticate(object sender, EventArgs e)
{
app = (HttpApplication)sender;
HttpRequest req = app.Request;
HttpResponse res = app.Response;

string loginUrl = ConfigurationSettings.AppSettings[LOGINURL_KEY];
if(loginUrl == null || loginUrl.Trim() == String.Empty)
{
throw new Exception(" CustomAuthentication.LoginUrl entry not found in appSettings section of Web.config");
}

string cookieName = ConfigurationSettings.AppSettings[AUTHENTICATION_COOKIE_KEY];
if(cookieName == null || cookieName.Trim() == String.Empty)
{
throw new Exception(" CustomAuthentication.Cookie.Name entry not found in appSettings section section of Web.config");
}

int i = req.Path.LastIndexOf("/");
string page = req.Path.Substring(i+1, (req.Path.Length - (i + 1)));

            int j = loginUrl.LastIndexOf("/");
            string loginPage = loginUrl.Substring(j + 1, (loginUrl.Length - (j + 1)));

            if (req.Cookies.Count > 0 && req.Cookies[cookieName.ToUpper()] != null)
            {
                HttpCookie cookie = req.Cookies[cookieName.ToUpper()];
                if (cookie != null)
                {
                    string str = cookie.Value;
                    CustomIdentity userIdentity = CustomAuthentication.Decrypt(str);
                    string[] roles = userIdentity.UserRoles.Split(new char[] { '|' });
                    ArrayList arrRoles = new ArrayList();
                    arrRoles.InsertRange(0, roles);
                    CustomPrincipal principal = new CustomPrincipal(userIdentity, arrRoles);
                    app.Context.User = principal;
                }
            }
}

public void Dispose()
{
} --------------------编程问答-------------------- 我顶 --------------------编程问答-------------------- rom gold --------------------编程问答-------------------- 另外 在页面上新增 一个空间,并且将控件的AutoPostBack设置为true 也会使AuthenticateRequest 被重复执行多次。
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,