简体   繁体   中英

Proper way to initialize gettext in runtime in asp.net / monodevelop

I am trying to get localization to work in an asp.net mvc project using monodevelop on mac. I have added a translation project and translated the text 'Welcome' in danish.

public class HomeController : Controller
{
    public ActionResult Index ()
    {
        var culture = CultureInfo.CreateSpecificCulture("da");      
        System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
        System.Threading.Thread.CurrentThread.CurrentCulture = culture;
        Mono.Unix.Catalog.Init("i8n1", "./locale");
        ViewData ["Message"] = Mono.Unix.Catalog.GetString("Welcome");
        return View ();
    }
}

But the text does not get translated. Any ideas?

Mono.Unix.Catalog is not suitable for ASP.NET. It uses a 'per environment' approach whereas for ASP.NET you need a 'per thread' approach.

This library is definitely worth a look as an alternative http://sourceforge.net/p/gettextnet/

For reference: http://lists.ximian.com/pipermail/mono-devel-list/2008-March/027174.html

You'll need the full path to your locale folder.

MonoDevelop does something like this (edited for brevity)

string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
location = Path.GetDirectoryName(location);

string catalogPath = Path.Combine (location, "locale");

Catalog.Init ("monodevelop", catalogPath);

The answer is here: http://mono.1490590.n4.nabble.com/Mono-Unix-Catalog-Init-where-does-it-get-the-locale-from-td1532586.html

public static void Main (string[] args)
    {
        var culture = CultureInfo.CreateSpecificCulture ("de");
        Thread.CurrentThread.CurrentCulture = culture;
        Environment.SetEnvironmentVariable ("LANGUAGE", "de_DE"); 
        Catalog.Init ("i8n1", "./locale");

        Console.WriteLine (Catalog.GetString("Hello World!"));
    }

And it works for me on Ubuntu/Mono. Thanks to Vladimir for good question and to Jonathan for great answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM