Home > DeveloperSection > Forums > Why would HttpContext not contain a “Host” header?
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    August-25-2014 2:03 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 749  View(s)
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?



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    August-25-2014 2:29 AM

Hi jayden, 
try this:

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


Don't want to miss updates? Please click the below button!

Follow MindStick