[Original] ASP. net mvc 3 Razor multi-language reference solution supplement

Source: Internet
Author: User
Tags reflector

Said that when Zhang antique lent his wife to Li chenglong, the last result was a loan. In this case, both sides should blame: Zhang's antique motives are not pure, and Li chenglong is not honest, but in general, it is very addictive to take advantage of cheap people.

Nobody knows Reflector ,. NET users who have been using it for many years may no longer need to look at it. NET source code. I have read it before, and I can guess a lot of implementation methods and operating principles, but it is not commonly used for beginners and users who want to view it. NET source code, without Reflector is really uncomfortable. But two days ago, I suddenly heard a message, and Reflector actually paid for it !!! Such a useful tool is not free to use ??? It's like Zhang zhixing lent his wife to Li chenglong and asked Li chenglong to sing songs every night. He was so happy that one day he suddenly wanted to return his wife. Li chenglong was lonely and cold, and it was definitely not a taste, but fortunately, what Zhang antique lent out is a living thing. I don't know why I decided to keep up with Li chenglong and let Zhang antique have a wealth of money. But Reflector is a dead thing, and you have to follow the commands of the master after a thousand calls. Too far...

Enter the subject:

As mentioned above, use System. resources. resXResourceReader (System. windows. forms. dll) type to obtain the items in the resource file to implement Localization under MVC, but this scheme can only be regarded as a prototype or reference scheme. Today I have studied this type, fortunately, my colleague has a Reflector who has not been upgraded. (I accidentally clicked the button for an automatic upgrade. This should not be an infringement.) I opened the ResXResourceReader implementation principle, it turns out that this type of resource item is obtained by parsing XML and put in an IDictionaryEnumerator.

This makes it clear that this type can be used securely in Web programs. The main overhead of this type is reading and parsing resx files. I usually prefer to use cache to solve performance problems in some scenarios. this time there is no exception ,. in net4. runtime. caching. memoryCache hasn't been used yet, so I took it out as a trainer.

For piapia, modify the above Code as follows:

    public static class LocalizationHelpers    {        public static string Lang(this HtmlHelper htmlhelper, string key)        {            var viewPath = (htmlhelper.ViewContext.View as BuildManagerCompiledView).ViewPath;            var viewName = viewPath.Substring(viewPath.LastIndexOf('/'), viewPath.Length - viewPath.LastIndexOf('/')).TrimStart('/');            var filePath = htmlhelper.ViewContext.HttpContext.Server.MapPath(viewPath.Substring(0, viewPath.LastIndexOf('/') + 1)) + "App_LocalResources";            var langs = htmlhelper.ViewContext.HttpContext.Request.UserLanguages;            string resxPath = string.Format(@"{0}\{1}.resx", filePath, viewName);            foreach (var lang in langs)            {                if (File.Exists(string.Format(@"{0}\{1}.{2}.resx", filePath, viewName, lang)))                {                    resxPath = string.Format(@"{0}\{1}.{2}.resx", filePath, viewName, lang);                    break;                }            }            var result = ResXCache.GetResValue(resxPath, key);            return result;        }        public static class ResXCache        {            public static string GetResValue(string file, string key)            {                ObjectCache cache = MemoryCache.Default;                IEnumerable<DictionaryEntry> resxs = null;                if (cache.Contains(file) == false)                {                    resxs = new ResXResourceReader(file).Cast<DictionaryEntry>();                    cache.Add(file, resxs, new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable });                }                else                {                    resxs = cache.GetCacheItem(file).Value as IEnumerable<DictionaryEntry>;                }                return (string)resxs.FirstOrDefault<DictionaryEntry>(x => x.Key.ToString() == key).Value;            }        }    }

OK. Basically, this solution can be used in the project.

Updated on April 9, March 19, and overwritten the Lang method, reducing the steps for verifying whether the resource file exists ----------------------------------------------------------------

    public static class LocalizationHelper    {        public static string Lang(this HtmlHelper htmlhelper, string key)        {            var viewPath = (htmlhelper.ViewContext.View as BuildManagerCompiledView).ViewPath;            var viewName = viewPath.Substring(viewPath.LastIndexOf('/'), viewPath.Length - viewPath.LastIndexOf('/')).TrimStart('/');            var filePath = htmlhelper.ViewContext.HttpContext.Server.MapPath(viewPath.Substring(0, viewPath.LastIndexOf('/') + 1)) + "App_LocalResources";            var langs = htmlhelper.ViewContext.HttpContext.Request.UserLanguages.Union<string>(new string[] { "" });            IEnumerable<DictionaryEntry> resxs = null;            foreach (var lang in langs)            {                var resxKey =                    string.IsNullOrWhiteSpace(lang) ? string.Format(@"{0}\{1}.resx", filePath, viewName) : string.Format(@"{0}\{1}.{2}.resx", filePath, viewName, lang);                resxs = GetResx(resxKey);                if (resxs != null) { break; }            }            return (string)resxs.FirstOrDefault<DictionaryEntry>(x => x.Key.ToString() == key).Value;        }        private static IEnumerable<DictionaryEntry> GetResx(string resxKey)        {            ObjectCache cache = MemoryCache.Default;            IEnumerable<DictionaryEntry> resxs = null;            if (cache.Contains(resxKey))            {                resxs = cache.GetCacheItem(resxKey).Value as IEnumerable<DictionaryEntry>;            }            else            {                if (File.Exists(resxKey))                {                    resxs = new ResXResourceReader(resxKey).Cast<DictionaryEntry>();                    cache.Add(resxKey, resxs, new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable });                }            }            return resxs;        }    }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.