我正在 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 如下(它比我想要的更复杂,因为需要将 sub .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() 在调试模式下的行为方式不同?它在发布模式下工作。我可以理解您不希望它在调试中捆绑和缩小,但我如何才能强制此捆绑始终以相同的方式工作?