使用OWIN和异步方法的多语言网站

时间:2015-08-20 21:31:38

标签: c# asynchronous internationalization async-await owin

背景

我正在使用IIS上的ASP.NET 4.6,C#,OWIN管道创建一个简单的多语言网站(Microsoft.Owin.Host.SystemWeb),许多异步方法调用和标准的全局资源文件(*.resx in App_GlobalResources)。该网站使用MVC5,WebAPI2和Autofac作为依赖解析器。

问题

我无法正确更改生成页面的区域设置/文化,因为异步方法每个请求使用多个线程,我找不到为与给定请求关联的每个线程设置Thread.Current[UI]Culture作为这些属性的方法没有同步。我还希望保持干净的代码而不使用“异步/等待文化配置”来搞乱有用的代码。

代码

Startup.cs

public void Configuration(IAppBuilder app)
{
    ...

    app.UseAutofacMiddleware(container);
    app.UseAutofacMvc();
    app.UseAutofacWebApi(httpConfiguration);
    app.UseWebApi(httpConfiguration);

    ...

    app.Use(async (ctx, next) =>
    {
        /* in production, detect based on current URL and/or cookie */
        var culture = new CultureInfo("pl_PL");

        CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = culture;

        await next.Invoke();
    });
}

SampleController.cs

public async Task<ActionResult> SayHello()
{
    // returns pl_PL message
    var msgA = Resources.Messages.HelloWorld; 

    await someService.doSthAsync();

    // returns system default (en_US) message
    var msgB = Resources.Messages.HelloWorld;

    return Content(msgA + " - " + msgB);
}
  1. 我应该按照建议in this SO answer创建自定义[AspNet]SynchronizationContext吗?如果是这样的话我应该怎么做?
  2. 我是否应该放弃全球资源作为翻译来源并使用其他方法?如果是这样,我可以使用什么(库?)?

1 个答案:

答案 0 :(得分:5)

使用the Owing Globalization Library怎么样,好像是为了这个目的而创建的。

您仍然可以使用您的resx来本地化您的资源,并且它具有出色的自定义功能:

public void Configuration(IAppBuilder app)
{
    ...
    app.UseGlobalization(new OwinGlobalizationOptions("en-US",true)
       .DisablePaths("Content", "bundles")
       .Add("fr-FR", true).AddCustomSeeker(new CultureFromPreferences()));
}

我测试了async / await的使用并保留了文化:

    public async Task<ActionResult> About()
    {
        var msgA = Resources.Resources.About;

        await Task.Delay(1000);

        var msgB = Resources.Resources.About;

        ViewBag.Message = msgA + " - " + msgB;

        return View();
    }

注意:我不是图书馆的作者,我以前碰巧使用过它。