WHY WOULD HTTPCONTEXT NOT CONTAIN A “HOST” HEADER?

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
 948  View(s)
Ratings:
Rate this:

In my MVC3 application I have a custom controller factory that has CreateController()method working as follows:

  public IController CreateController(RequestContext requestContext, string controllerName)

   {

       string host = requestContext.HttpContext.Request.Headers["Host"];

       if( !host.EndsWith( SomeHardcodedString ) ) { // FAILS HERE

           //some special action

       }

       //proceed with controller creation

   }

the problem is host is null sometimes - I see NullReferenceException for some requests and the exception stack trace points exactly at that line.

Why would null be retrieved here? How do I handle such cases?

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: Why would HttpContext not contain a “Host” header?

    Hi jayden, 

    try this:

    Use string host = requestContext.HttpContext.Request.Url.Host;

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!