这是我的情况...
public partial class CssController : Controller
{
public virtual ActionResult Merge(string[] files)
{
var builder = new StringBuilder();
foreach (var file in files)
{
var pathAllowed = Server.MapPath(Url.Content("~/Content/css"));
var normalizeFile = Server.MapPath(Url.Content(Path.Combine("~/Content/css", file)));
if (normalizeFile.StartsWith(pathAllowed) == false)
{
return HttpNotFound("Path not allowed");
}
if (System.IO.File.Exists(normalizeFile))
{
Response.AddFileDependency(normalizeFile);
builder.AppendLine(System.IO.File.ReadAllText(normalizeFile));
}
}
Response.Cache.VaryByParams["files"] = true;
Response.Cache.SetLastModifiedFromFileDependencies();
Response.Cache.SetETagFromFileDependencies();
Response.Cache.SetCacheability(HttpCacheability.Public);
var css = dotless.Core.Less.Parse(builder.ToString(), new DotlessConfiguration());
return Content(css, "text/css");
}
public string Index()
{
Response.ContentType = "text/css";
return Razor.Parse(System.IO.File.ReadAllText(Server.MapPath("~/Content/css/Global.css")));
}
}
}
现在,公共(public)操作方法用于在一次请求中获取所有 css 文件。还重述并解析 .less 文件。由于缺乏支持 .less 的编辑器,我们转向 Razor 来解析我们的 css。底部的字符串方法显示了我们正在尝试执行的操作。简单明了,我怎样才能集成这两种方法而不出现错误。
在我们的布局中,我们正在使用这个
<link rel="stylesheet" type="text/css" href="@Url.ActionLinkWithArray("Merge", "Css", new { files = new[] { "StoreManager.less" } })" />
根据一个请求提取所有文件。然而,当我想使用 RazorEngine 时,这是使用 .less 配置。
我希望这能解释我需要做什么。有人可以帮忙吗?
最佳答案
我最喜欢的解决方案是 Cassette作者:安德鲁·戴维。
在您的_Layout.cshtml
中,您:
<head>
<title>@ViewBag.Title</title>
@Assets.Scripts.Render()
</head>
在任何需要 JavaScript 的 View 中:
@{
ViewBag.Title = "My Page";
Assets.Scripts.Reference("scripts/utils/date.js");
Assets.Scripts.Reference("scripts/widgets/calendar.js");
}
这将缩小(包括 Less
)并将所有脚本和 CSS 压缩为每个文件。
这可能有帮助,也可能没有帮助,但确实会让事情变得容易。看起来您正在寻找当前问题的解决方案,但这绝对是一种替代方案。
关于css - 使用 Razor 引擎渲染 CSS + 启用一个请求多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6878226/