Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting hostname in MVC controller constructor

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?

like image 852
Ben Power Avatar asked Nov 06 '13 07:11

Ben Power


People also ask

Can we use constructor in MVC controller?

ASP.NET Core MVC controllers request dependencies explicitly via constructors.

How controller is called in MVC?

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.

Can a controller have a constructor?

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.

What is constructor in ASP NET MVC?

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.


1 Answers

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.

like image 88
haim770 Avatar answered Oct 30 '22 13:10

haim770