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?
ASP.NET Core MVC controllers request dependencies explicitly via constructors.
A controller is just a class (for example, a Visual Basic or C# class). The sample ASP.NET MVC application includes a controller named HomeController. cs located in the Controllers folder.
ASP.NET MVC framework itself creates controller objects at run time. There is only one prerequisite, that is controller class must have a parameter less constructor.
A constructor is a special type of method of a C# class which invokes automatically when a new instance of a class is created. Constructor is used in object initialization and memory allocation of the class. Constructor is used to initialize private fields and their values of the class. A constructor can be overloaded.
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.
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