Search code examples
c#.netasp.net-web-api.net-4.5httpcontext

'context.Request' threw an exception of type 'System.Web.HttpException'


I am trying to use access HTTPContext inside Global.asax Application_Start() event.

        var context = HttpContext.Current;
        if (context != null)
        {
            if (context.Request != null) //Getting error here
            {
                  .....
            }
        }

When accessing context.Request I am getting 'context.Request' threw an exception of type 'System.Web.HttpException' exception.

In this case context.Request is not null but its throwing exception.

I used following code to identify if the Request property exists:

context.GetType().GetProperty("Request");

And I got following response.

{System.Web.HttpRequest Request}
    Attributes: None
    CanRead: true
    CanWrite: false
    CustomAttributes: Count = 0
    DeclaringType: {Name = "HttpContext" FullName = "System.Web.HttpContext"}
    GetMethod: {System.Web.HttpRequest get_Request()}
    IsSpecialName: false
    MemberType: Property
    MetadataToken: 385876876
    Module: {System.Web.dll}
    Name: "Request"
    PropertyType: {Name = "HttpRequest" FullName = "System.Web.HttpRequest"}
    ReflectedType: {Name = "HttpContext" FullName = "System.Web.HttpContext"}
    SetMethod: null

I am not sure how to confirm if context.Request exists and is not null ?

Solution

  • From the documentation:

    ASP.NET will throw an exception if you try to use this property when the HttpRequest object is not available. For example, this would be true in the Application_Start method of the Global.asax file, or in a method that is called from the Application_Start method. At that time no HTTP request has been created yet.

    Application_Start isn't meant to handle a specific request, so you would need to move what you're doing into the handler for a different event, like BeginRequest.