尝试访问Request.Url时,ASP.NET HttpModule失败,出现NullReference异常

我有一个HttpModule来处理每个HttpRequest的一些自定义逻辑,并且由于某种原因,在我尝试访问HttpRequest.Url的情况下,它会抛出NullReferenceException错误.

在访问Url之前,我正在检查HttpContext是否在那里,而Request对象不是null.这是堆栈跟踪:

[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请求期间发生这种情

最佳答案 你能尝试从HttpContext.Current获取HttpContext吗?

public class MyHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += this.BeginRequestEventHandler;
    }

    private void BeginRequestEventHandler(object sender, EventArgs e)
    {
        var httpContext = HttpContext.Current;
        ...
    }
}
点赞