gpt4 book ai didi

c# - MVC4 按主机名 bundle

转载 作者:太空狗 更新时间:2023-10-29 20:34:21 26 4
gpt4 key购买 nike

我是 MVC 新手。

我知道如何创建 bundle ,这很简单,而且是一个很棒的功能:

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

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

如何根据主机名让一个包包含不同的文件?在我的 RegisterBundles 所在的应用程序开始处(就像在我开始使用的 MVC 标准互联网应用程序中一样)我什至还不知道主机名。

最佳实践是什么?

如果我在注册 bundle 时有可用的主机名,我可以为当前主机名选择正确的 .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"。

怎么样?

最佳答案

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

var host = Request.Url.Host;

在您注册您的 bundle 之前,并根据返回的值有条件地注册您的 bundle 。

更新使用域 key 注册所有 bundle :

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

然后在所有 Controller 都继承的基础 Controller 中,您可以构建包名称以传递给 View :

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

然后在布局或 View 中:

@Styles.Render(ViewBag.BundleName)

关于c# - MVC4 按主机名 bundle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14162032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com