我一直在 MVC 中使用 Bundles 将所有脚本和 CSS 打包在一起,这很棒,但是...... 有没有办法将共享项目库中的资源中的脚本或CSS包含在 bundle 中,或者有人知道类似 bundle 的东西可以做到这一点吗?
最佳答案
我可能会开始编写一个自定义 bundle 转换类来读取您需要的资源并返回其内容和内容类型:
public class ResourceTransform : IBundleTransform
{
public void Process(BundleContext context, BundleResponse response)
{
string result;
using (Stream stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("YourAssemblyNamespace.YourResourceFolder.YourFile.css"))
{
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
response.ContentType = "text/css";
response.Content = result;
}
}
对于生产用途,您可能希望减少 ResourceTransform
类的硬编码,并将所需的资源作为参数或属性发送,但您明白了。
这样您就可以将此 bundle 添加到您的收藏中:
Bundle resources = new Bundle("~/css/resources");
resources.Transforms.Add(new ResourceTransform());
resources.Transforms.Add(new CssMinify());
bundles.Add(resources);
关于asp.net-mvc - 将来自 MVC 程序集中的资源的脚本和 CSS bundle 在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959974/