我需要将一堆文件合并到一个“文件”中。但我还需要其中一些文件是动态的,所以我有返回动态资源的操作。例如
[OutputCache(VaryByParam = "culture", Duration = 3600)]
public ActionResult Settings(string culture)
{
CultureInfo cultureInfo;
try
{
cultureInfo = new CultureInfo(culture);
}
catch
{
cultureInfo = Configuration.Current.DefaultCulture;
}
var sb = new StringBuilder();
sb.AppendFormat("Cms.Settings.Language = '{0}';", cultureInfo.TwoLetterISOLanguageName);
sb.AppendFormat("Cms.Settings.DayNames = [{0}];", string.Join(",", cultureInfo.DateTimeFormat.DayNames.Select(d => "\"" + d + "\"")));
sb.AppendFormat("Cms.Settings.ShortDayNames = [{0}];", string.Join(",", cultureInfo.DateTimeFormat.AbbreviatedDayNames.Select(d => "\"" + d + "\"")));
sb.AppendFormat("Cms.Settings.FirstDay = {0};", (int)cultureInfo.DateTimeFormat.FirstDayOfWeek);
sb.AppendFormat("Cms.Settings.ShortMonthNames = [{0}];", string.Join(",", cultureInfo.DateTimeFormat.AbbreviatedMonthNames.Take(12).Select(m => "\"" + m + "\"")));
var languages = new[]{cultureInfo.TwoLetterISOLanguageName};
var keys = translator.GetKeys(languages[0]);
foreach (var key in keys)
{
sb.AppendFormat("Cms.Settings.Texts['{0}'] = '{1}';", key, translator.GetText(key, key, languages));
}
// TODO: from settings
sb.AppendFormat("Cms.Settings.IconDir = '{0}';", VirtualPathUtility.ToAbsolute("~/img/icons/"));
return JavaScript(sb.ToString());
}
我想要做的是将这些物理文件和 ActionResults 合并到一个“文件”中。我已经做了这个动作来进行组合,但我不知道通过路径获取动作输出的简单方法。
// files is like "jquery.js,/js/settings?culture=fi,jquery-ui.js,..."
[OutputCache(VaryByParam = "files", Duration=3600)]
public ActionResult Bundle(string files)
{
var paths = files.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var sb = new StringBuilder();
foreach (var path in paths)
{
appendFile(sb, path);
}
return JavaScript(sb.ToString());
}
private void appendFile(StringBuilder sb, string path)
{
if (/* path is file on disk */)
{
var filename = Server.MapPath(path);
if (!System.IO.File.Exists(filename))
{
return;
}
sb.Append(System.IO.File.ReadAllText(filename));
}
else if(/* is action */)
{
// how do I get the output?
var output = getActionOutput(path);
sb.Append(output);
}
}
我尝试的另一个选项是将 VirtualPathProvider 用于动态文件,但由于某种原因,没有为不在磁盘上的文件调用“GetFile”。
public class JsVirtualPathProvider : VirtualPathProvider
{
public override bool FileExists(string virtualPath)
{
if (virtualPath == "~/js/settings/fi.js")
{
// this was called
return true;
}
return base.FileExists(virtualPath);
}
public override VirtualFile GetFile(string virtualPath)
{
// never called for this "file"?
if (virtualPath == "~/js/settings/fi.js")
{
return new JsFile(virtualPath, "Cms.Settings.Foo = 'Bar';");
}
return base.GetFile(virtualPath);
}
class JsFile : VirtualFile
{
private readonly string content;
public JsFile(string virtualPath, string content) : base(virtualPath)
{
this.content = content;
}
public override Stream Open()
{
return new MemoryStream(Encoding.UTF8.GetBytes(content), false);
}
}
}
将物理文件与动态/虚拟文件结合起来的最简单方法是什么?