Getting hostname in MVC controller constructor

asp.net-mvc entity-framework

Question

Is it possible to get the current hostname from the controller constructor?

Both the Request and HttpContext objects are null, so Request.Url yields nothing.

public class HomeController : Controller
{
    private readonly MyEntities _entities;

    public HomeController()
    {
        //
        var hostname = Request.Url;
        if (hostname.Contains("localhost")) EFConnectionStringName="localhost";
        else EFConnectionStringName="default";
        _entities = new MyEntities(EFConnectionStringName);
    }
...

The greater problem I am trying to solve here is to choose a connection string for Entity Framework based upon the hostname. Ideas?

1
13
12/17/2013 8:43:51 AM

Accepted Answer

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.

18
4/16/2015 3:05:21 PM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow