我根据Nadeem Afana's blog使用类似于Mads Kristensen's blog的脚本转换器来本地化MVC。问题是bundle在Application_Start方法中注册。这会导致脚本以一种默认语言翻译并存储在浏览器/服务器缓存中。改变语言/文化不会产生他们的语言等价物。是否可以像Views一样实现缓存配置文件VaryByCustom =“culture”?有没有更好的练习/解决方案?是否可以将HTML5应用程序缓存与已翻译的脚本一起使用?
脚本翻译类:
public class ScriptTranslator : IBundleTransform {
public ScriptTranslator(ResourceManager manager) {
RM = manager;
}
public void Process(BundleContext context, BundleResponse response) {
response.Content = TranslateScript(response.Content);
}
private static ResourceManager RM;
private static Regex REGEXP = new Regex( @"translate\(""([^\))]*)""\)", RegexOptions.Singleline | RegexOptions.Compiled);
private string TranslateScript(string text) {
MatchCollection matches = REGEXP.Matches(text);
foreach (Match key in matches) {
object obj = RM.GetObject(kay.Groups[1].Value);
if (obj != null) {
text = text.Replace(kay.Value, CleanText(obj.ToString()));
}
}
return text;
}
private static string CleanText(string text) {
return string.Format("\"{0}\"", text.Replace("\\", "\\\\"));
}
}
使用自定义工具命名空间Resources.Javascript的资源文件;我的包配置是:
public class BundleConfig {
public static void RegisterBundles(BundleCollection bundles) {
var DEFAULT_SCRIPT_PATH = "~/Scripts/Modules/";
var DEFAULT_SCRIPT_BOUNDLE_PATH = "~/ScriptBundles/";
var mainBoundle = new ScriptBundle(DEFAULT_SCRIPT_BOUNDLE_PATH + "main")
.Include(DEFAULT_SCRIPT_PATH + "test.js");
mainBoundle.Transforms.Clear();
mainBoundle.Transforms.Add(new ScriptTranslator(Resources.JavaScript.test.ResourceManager));
mainBoundle.Transforms.Add(new JsMinify());
bundles.Add(mainBoundle);
}
}
答案 0 :(得分:1)
我们针对此问题的解决方案不仅是通过控制器/操作组合存储不同的包,还通过CurrentUICulture存储。
string.Format("scriptsDependency{0}{1}_{2}", controler, action, Thread.CurrentThread.CurrentUICulture.Name);
我还建议存储静态库,如JQuery或Bootstrap。但对于动态内容,我会推荐NoCache政策。
public class NonCacheableTransformer : IBundleTransform
{
public void Process(BundleContext context, BundleResponse response)
{
context.UseServerCache = false;
response.Cacheability = HttpCacheability.NoCache;
}
}