asp.net-mvc 在MVC控制器构造函数中获取主机名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19806537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:17:37  来源:igfitidea点击:

Getting hostname in MVC controller constructor

asp.net-mvcentity-framework

提问by Ben Power

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.

Request 和 HttpContext 对象都为空,因此 Request.Url 不会产生任何结果。

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?

我在这里尝试解决的更大问题是根据主机名为实体框架选择一个连接字符串。想法?

回答by haim770

Requestis indeed null during the constructionof your Controller. Try this instead:

Request构建您的控制器期间确实为空。试试这个:

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.Urlwill not return the hostname but a Uriobject from which you can extract the hostname using Url.Host.

另外,请注意,它Request.Url不会返回主机名,而是返回一个Uri对象,您可以使用Url.Host.

See MSDN.

请参阅MSDN

回答by oxfn

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.Urlis an Uriobject, so you should check Request.Url.Host

注意,这Request.Url是一个Uri对象,所以你应该检查Request.Url.Host

回答by Brian Adriance

Request URL's host doesn't necessarily have to match the hosting server name. For example if you're using DNS CNAMEs or loadbalancers.

请求 URL 的主机不一定必须与托管服务器名称匹配。例如,如果您使用 DNS CNAME 或负载均衡器。

If you'd like the machine name of the server hosting the code, try this in your controller action:

如果您想要托管代码的服务器的机器名称,请在您的控制器操作中尝试:

string hostingMachineName = HttpContext.ApplicationInstance.Server.MachineName;