最近我正在实现一个 HttpMoudle。并坚持所说的错误System.NullReferenceException: Object reference not set to an instance of an object.
这是我的代码。
public class MyHttpModuler : IHttpModule
{
private static IAuthProvider authProvider=null;
#region IHttpModule members
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
public void Dispose()
{
authProvider.Dispose();
authProvider = null;
}
public void Init(HttpApplication application)
{
authProvider = new BasicAuthProvider("achievo");
application.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpRequest request = app.Request;
HttpResponse response = app.Response;
TryAuthenticate(app);
}
#endregion
#region private method
/// <summary>
/// Tries to authenticate the user
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
private bool TryAuthenticate(HttpApplication context)
{
string authHeader = context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
if (authHeader.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase))
{
string userNameAndPassword = Encoding.Default.GetString(
Convert.FromBase64String(authHeader.Substring(6)));
string[] parts = userNameAndPassword.Split(':');
if (authProvider.IsValidUser(parts[0], parts[1]))
{
//the authProvider object sometimes is null .Why?
return true;
}
}
}
return false;
}
#endregion
}
public class BasicAuthProvider : IAuthProvider
{
#region IAuthProvider Members
public string DomainName { get; set; }
public BasicAuthProvider(string sDmName)
{
DomainName = sDmName;
}
public bool IsValidUser(string userName, string password)
{
string sFullName = "LDAP://" + DomainName + ".com";
bool bLogin = ADHelper.IsAuthenticated(sFullName, DomainName + @"\" + userName, password);
return bLogin;
}
public bool IsRequestAllowed(HttpRequest request,string sName)
{
return sName == "joe.wang";
}
public void Dispose()
{
}
#endregion
}
尤其是当多个用户进入网站时。发生 NullReferenceException 异常。当我调试时,我发现有时Init
方法可能不会被调用。也许这就是发生异常的原因。任何人都可以帮我检查一下吗?谢谢