I thought I could use the previous multi-language solution for programming. I didn't expect the first official page to be stuck. Why, because htmlhelper can only find the view of the current request, if this view uses layout or partial, it will stop. Through some attempts, we found that using htmlhelper. the viewdatacontainer attribute can be used to obtain a webviewpage object. The virtualpath object in this object represents the physical file (. cshtml), So modify the Code as follows:
Public static class localizationhelper {public static string Lang (this htmlhelper, string key) {var viewpath = (htmlhelper. viewdatacontainer as webviewpage ). virtualpath; 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. userages. 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 ;}}