ASP.NET HttpModule does not work with NullReference exception when trying to access Request.Url

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;
        // process url
    }
}

This happens in rare cases, but looks critical if it happens while processing regular HTTP requests.

+4
3

HttpContext HttpContext.Current?

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

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

, , .NET Framework . , , unsafe, , - - .

, IIS , , , , , - .

, IIS https://social.technet.microsoft.com/wiki/contents/articles/19863.list-of-iis-7-5-related-hotfixes-post-sp1-for-windows-7-sp1-and-windows-server-2008-r2-sp1.aspx

, Request.Path Request.FilePath URL- try-catch .

+1

Try to do this, it should not have problems:

if (httpContext.Request != null)
{
    if (httpContext.Request.Url != null)
    {
        var url = httpContext.Request.Url;
    }
}
0
source

Source: https://habr.com/ru/post/1671942/


All Articles