我正在实现MVC4中的打包和压缩支持,并设置它可以自动为我编译Bootstrap .less文件。我在BundleConfig.cs文件中有以下代码:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
// base bundles that come with MVC 4
var bootstrapBundle = new Bundle("~/bundles/bootstrap").Include("~/Content/less/bootstrap.less");
bootstrapBundle.Transforms.Add(new TwitterBootstrapLessTransform());
bootstrapBundle.Transforms.Add(new CssMinify());
bundles.Add(bootstrapBundle);
}
}
TwitterBootsrapLessTransform的定义如下(由于需要将子.less文件导入dotLess中,因此比我想象中更为复杂)。
public class TwitterBootstrapLessTransform : IBundleTransform
{
public static string BundlePath { get; private set; }
public void Process(BundleContext context, BundleResponse response)
{
setBasePath(context);
var config = new DotlessConfiguration(DotlessConfiguration.GetDefault());
config.LessSource = typeof(TwitterBootstrapLessMinifyBundleFileReader);
response.Content = Less.Parse(response.Content, config);
response.ContentType = "text/css";
}
private void setBasePath(BundleContext context)
{
BundlePath = context.HttpContext.Server.MapPath("~/Content/less" + "/imports" + "/");
}
}
public class TwitterBootstrapLessMinifyBundleFileReader : IFileReader
{
public IPathResolver PathResolver { get; set; }
private string basePath;
public TwitterBootstrapLessMinifyBundleFileReader(): this(new RelativePathResolver())
{
}
public TwitterBootstrapLessMinifyBundleFileReader(IPathResolver pathResolver)
{
PathResolver = pathResolver;
basePath = TwitterBootstrapLessTransform.BundlePath;
}
public bool DoesFileExist(string fileName)
{
fileName = PathResolver.GetFullPath(basePath + fileName);
return File.Exists(fileName);
}
public byte[] GetBinaryFileContents(string fileName)
{
throw new System.NotImplementedException();
}
public string GetFileContents(string fileName)
{
fileName = PathResolver.GetFullPath(basePath + fileName);
return File.ReadAllText(fileName);
}
}
在我的基本 Layout.cshtml 页面上,我尝试通过以下方式呈现 css 文件
@Styles.Render("~/bundles/bootstrap");
正如MVC教程所建议的那样,但客户端浏览器最终请求的文件是什么。http://localhost:53729/Content/less/bootstrap.less
这会导致一个错误。如果我将以下链接放入基本布局页面中,它会按预期工作。
<link href="~/bundles/bootstrap" rel="stylesheet" type="text/css" />
为什么在调试模式下 @Styles.Render() 的行为与发布模式不同?在发布模式下它能够正常工作。我可以理解你不希望在调试模式下进行打包和压缩,但是我如何强制使该捆绑包始终以相同的方式工作呢?