如何使用MVC4在Controller中获取主机

时间:2015-03-06 14:42:30

标签: c# asp.net-mvc model-view-controller controller

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

我需要在我的控制器中获取一个HOST以定义此角色。

有些人喜欢这样:

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

    if (host == "mycustomhost.com")
    {
        ViewBag.Theme = "CustomTheme";
    }
    else
    {
        ViewBag.Theme = "DefaultTheme";
    }
}

2 个答案:

答案 0 :(得分:2)

你尝试过这样的事吗?

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";
    }
}

答案 1 :(得分:0)

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);
}