开发者

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

开发者 https://www.devze.com 2023-04-08 17:41 出处:网络
I am trying to 开发者_C百科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.

I am trying to 开发者_C百科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?


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);


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号