我有一个 HttpModule
用于处理每个 HttpRequest
的自定义逻辑,但是在某些情况下,当我尝试访问 HttpRequest.Url
时会抛出 NullReferenceException
错误。
在访问 Url
之前,我检查了是否存在 HttpContext
和 Request
对象不为空。以下是堆栈跟踪:
[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
我还查看了.NET源代码,但未能找到NullReference的位置: https://referencesource.microsoft.com/#System.Web/Hosting/IIS7WorkerRequest.cs,68b1222d24e7bd28 以下是代码:
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;
// process url
}
}
虽然这种情况很少见,但只要发生在处理常规的HTTP请求时,看起来就非常关键。