Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would HttpContext not contain a "Host" header?

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?

like image 205
sharptooth Avatar asked Dec 13 '11 13:12

sharptooth


People also ask

Is http host header required?

The HTTP host header is a request header that specifies the domain that a client (browser) wants to access. This header is necessary because it is pretty standard for servers to host websites and applications at the same IP address.

What is Http_host header?

The Host request header specifies the host and port number of the server to which the request is being sent. If no port is included, the default port for the service requested is implied (e.g., 443 for an HTTPS URL, and 80 for an HTTP URL). A Host header field must be sent in all HTTP/1.1 request messages.


2 Answers

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

like image 83
Arturo Martinez Avatar answered Sep 21 '22 19:09

Arturo Martinez


To handle it, you might want to try something like:

var host = requestContext.HttpContext.Request.Url.Host;

if (host != null)
    if(!host.EndsWith("SomeHardcodedString")) 
else
   // Handle it
like image 34
syneptody Avatar answered Sep 21 '22 19:09

syneptody