I have HttpModuleto handle some user logic with each HttpRequest, and for some reason in rare cases it throws an error NullReferenceExceptionwhen I try to access HttpRequest.Url.
Before accessing, UrlI check if the object exists HttpContextand Requestis not null. Here is the stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Hosting.IIS7WorkerRequest.GetQueryStringRawBytes() +55
System.Web.HttpRequest.get_QueryStringText() +76
System.Web.HttpRequest.BuildUrl(Func`1 pathAccessor) +42
System.Web.HttpRequest.get_Url() +88
MyHttpModule.BeginRequestEventHandler(Object sender, EventArgs e) at +xx
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +175
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +168
I also checked the .NET source for more information and could not find a place for NullReference:
https://referencesource.microsoft.com/#System.Web/Hosting/IIS7WorkerRequest.cs,68b1222d24e7bd28
Here is the code:
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += this.BeginRequestEventHandler;
}
private void BeginRequestEventHandler(object sender, EventArgs e)
{
var httpContext = ((HttpApplication)sender).Context;
if (httpContext == null || httpContext.Request == null)
{
return;
}
var url = httpContext.Request.Url;
}
}
This happens in rare cases, but looks critical if it happens while processing regular HTTP requests.