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?
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.
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.
Use string host = requestContext.HttpContext.Request.Url.Host;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With