如何使用 MVC4 在控制器中获取主机

How can I get host in a Controller using MVC4

我想获得一个主机名以在主机上应用特定角色,因为我为同一个应用程序文件夹托管了 2 个网站。

我需要在我的控制器中获得一个主机来定义这个角色。

有些像这样:

public 覆盖 void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);

    如果(主机 == "mycustomhost.com")
    {
        ViewBag.Theme = "CustomTheme";
    }
    别的
    {
        ViewBag.Theme = "DefaultTheme";
    }
}

你试过这样的东西吗?

public override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);

    var customHost = ConfigurationManager.AppSettings["CustomHost"];
    string theme = String.Empty;

    if (customHost.ToLower().Contains(requestContext.HttpContext.Request.Url.Host.ToLower()))
    {
        ViewBag.Theme = "CustomTheme";
    }
    else
    {
        ViewBag.Theme = "DefaultTheme";
    }
}
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);
}