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?
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