ASP.NET本地化
发布时间:2020-12-16 09:35:26  所属栏目:asp.Net  来源:网络整理 
            导读:在本地化ASP.NET应用程序(MVC或webforms,无关紧要)时,如何处理资源文件中的 HTML字符串?特别是,如何处理带有嵌入式动态链接的段落?到目前为止,我的策略是使用某种占位符来表示href属性值,并在运行时将其替换为实际的URL,但这似乎充满了乐趣. 例如,假设我的
                
                
                
            | 
 在本地化ASP.NET应用程序(MVC或webforms,无关紧要)时,如何处理资源文件中的 
 HTML字符串?特别是,如何处理带有嵌入式动态链接的段落?到目前为止,我的策略是使用某种占位符来表示href属性值,并在运行时将其替换为实际的URL,但这似乎充满了乐趣. 
  
  例如,假设我的副本是: Thank you for registering. Click 
<a href="{prefs_url}">here</a> 
to update your preferences.
To login and begin using the app,click 
<a href="{login_url}">here</a>.使用MVC(Razor),可能很简单: <p>@Resources.Strings.ThankYouMessage</p> 现在变成了 <p>@Resources.Strings.ThankYouMessage
     .Replace("{prefs_url}",Url.Action("Preferences","User"))
     .Replace("{login_url}",Url.Action("Login","User"))</p>这并不可怕,但我想我只是想知道是否有更好的方法? 解决方法
 除了一些语法和性能调整之外,没有更好的方法.例如,您可以添加缓存层,以便不对每个请求执行这些字符串操作.像这样的东西: 
  
  
  <p>@Resources.LocalizedStrings.ThankYouMessage</p> 它调用一个函数可能是这样的: Localize("ThankYouMessage",Resources.Strings.ThankYouMessage)它通过资源文化进行哈希表查找: //use Hashtable instead of Dictionary<> because DictionaryBase is not thread safe.
private static System.Collections.Hashtable _cache = 
    System.Collections.Hashtable.Synchronized(new Hashtable());
public static string Localize(string resourceName,string resourceContent) {
    string cultureName = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
    if (string.IsNullOrEmpty(resourceName))
        throw new ArgumentException("'resourceName' is null or empty.");
    string cacheKey = resourceName + "/" + cultureName;
    object o = _cache[cacheKey];
    if (null == o) { //first generation; add it to the cache.
        _cache[cacheKey] = o = ReplaceTokensWithValues(resourceContent);
    }
    return o as string;
}注意对ReplaceTokensWithValues()的调用.这是包含所有“不可怕”的字符串替换函数的函数: public static string ReplaceTokensWithValues(string s) {
    return s.Replace("{prefs_url}","User"))
       .Replace("{login_url}","User")
       .Replace("{any_other_stuff}","random stuff");
}通过使用上面的缓存方法,每个文化只调用一次ReplaceTokensWithValues(),每个资源调用一次应用程序的生命周期 – 而不是每个资源调用一次.差异可以是100对1,000,000的量级. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
相关内容
- WCF休息 – 最佳做法是什么?
- azure – ASP.NET 5(RC1)Bad Gateway:指定的CGI应用程序遇
- asp.net服务器负载均衡设置 – 它如何影响会话
- asp.net-mvc-4 – SimpleMembershipProvider:webpages_Mem
- asp.net-core – 模型集合上的ModelBinding
- asp.net-mvc – 如何动态预选ASP.NET MVC中html.DropDownli
- asp.net – 304未修改静态文件
- asp.net-mvc – ASP.NET MVC – 本地化路由
- asp.net-mvc-5 – 更改消息“密码必须至少包含一个非字母或
- TFS 2015构建:是否可以在存储库映射中使用变量?
推荐文章
            站长推荐
            
        热点阅读
            