Getting hostname in MVC controller constructor

Request is indeed null during the construction of your Controller. Try this instead:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    var hostname = requestContext.HttpContext.Request.Url.Host;

    // do something based on 'hostname' value
    // ....

    base.Initialize(requestContext);
}

Also, please note that Request.Url will not return the hostname but a Uri object from which you can extract the hostname using Url.Host.

See MSDN.


Try this:

public class HomeController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        Debug.Print("Host:" + Request.Url.Host); // Accessible here
        if (Request.Url.Host == "localhost")
        {
            // Do what you want for localhost
        }
    }
}

Note, that Request.Url is an Uri object, so you should check Request.Url.Host