MVC4按主机名捆绑

本文关键字:主机 MVC4 | 更新日期: 2023-09-27 17:50:38

我是MVC新手。

我知道如何创建包,这很容易,这是一个伟大的特性:

  bundles.Add(new StyleBundle("~/content/css").Include(
    "~/content/main.css",
    "~/content/footer.css",
    "~/content/sprite.css"
    ));

但是假设你的应用程序可以在不同的域下访问,并且根据主机名使用不同的css提供不同的内容。

如何让一个包根据主机名包含不同的文件?在应用程序开始时,我的RegisterBundles是(就像在MVC标准的互联网应用程序我开始),我甚至不知道主机名。

最佳实践是什么?

如果我在注册包时有可用的主机名,我可以为当前主机名选择正确的.css文件。例如,我可以在应用程序开始请求时注册bundle,并以某种方式检查它是否已经注册,如果没有,为请求的主机名选择正确的文件并注册它吗?

如果是,如何处理?

编辑1

在过去的两个小时里,我对这个话题进行了更深入的研究,让我提出我的解决方案,希望比我更熟悉MVC的人可以纠正我的方法,如果错误的话。

我取代了

:

@Styles.Render("~/Content/css")

:

@Html.DomainStyle("~/Content/css")

这只是一个简单的帮助:

public static class HtmlExtensions
{
  public static IHtmlString DomainStyle(this HtmlHelper helper, string p)
  {
    string np = mynamespace.BundleConfig.RefreshBundleFor(System.Web.Optimization.BundleTable.Bundles, "~/Content/css");
    if (!string.IsNullOrEmpty(np))
      return Styles.Render(np);
    else
    {
      return Styles.Render(p);
    }
  }
}

其中RefreshBundleFor为:

public static string RefreshBundleFor(BundleCollection bundles, string p)
{
  if (bundles.GetBundleFor(p) == null)
    return null;
  string domain = mynamespace.Utilities.RequestUtility.GetUpToSecondLevelDomain(HttpContext.Current.Request.Url);
  string key = p + "." + domain;
  if (bundles.GetBundleFor(key) == null)
  {
    StyleBundle nb = new StyleBundle(key);
    Bundle b = bundles.GetBundleFor(p);
    var bundleContext = new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, p);
    foreach (FileInfo file in b.EnumerateFiles(bundleContext))
    {
      string nf = file.DirectoryName + "''" + Path.GetFileNameWithoutExtension(file.Name) + "." + domain + file.Extension;
      if (!File.Exists(nf))
        nf = file.FullName;
      var basePath = HttpContext.Current.Server.MapPath("~/");
      if (nf.StartsWith(basePath))
      {
        nb.Include("~/" + nf.Substring(basePath.Length));
      }
    }
    bundles.Add(nb);
  }
  return key;
}

和GetUpToSecondLevelDomain只是返回二级域名的主机名,所以GetUpToSecondLevelDomain("www.foo.bar.com") = "bar.com"。

怎么样?

MVC4按主机名捆绑

过于复杂- Request对象在Application_Start中可用。只使用:

var host = Request.Url.Host;

,然后根据返回的值有条件地注册你的bundle。

用域密钥注册所有bundle:

StyleBundle("~/content/foo1.css")...
StyleBundle("~/content/foo2.css")...

然后在一个所有控制器都继承的基控制器中,你可以构建bundle的名字传递给视图:

var host = Request.Url.Host;  // whatever code you need to extract the domain like Split('.')[1]
ViewBag.BundleName = string.Format("~/content/{0}.css", host);

,然后在布局或视图中:

@Styles.Render(ViewBag.BundleName)