事件语言由 url 确定,然后在上设置
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
这样就可以从正确的资源文件中检索翻译。
在 Controller 上使用异步操作时,我们有一个后台线程,其中 Thread.CurrentThread.CurrentUICulture 设置回操作系统默认值。但在后台线程上我们也需要正确的语言。
我创建了一个 TaskFactory 扩展来将区域性传递到后台线程,它看起来像这样:
public static Task StartNew(this TaskFactory taskFactory, Action action, CultureInfo cultureInfo)
{
return taskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
action.Invoke();
});
}
这允许我在 Action Controller 中执行以下操作:
[HttpPost]
public void SearchAsync(ViewModel viewModel)
{
AsyncManager.OutstandingOperations.Increment();
AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
{
try
{
//Do Stuff
AsyncManager.Parameters["viewModel"] = viewModel;
}
catch (Exception e)
{
ModelState.AddModelError(string.Empty, ResxErrors.TechnicalErrorMessage);
}
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
}, Thread.CurrentThread.CurrentUICulture);
}
public ActionResult SearchCompleted(Task task, ViewModel viewModel)
{
//Wait for the main parent task to complete. Mainly to catch all exceptions.
try { task.Wait(); }
catch (AggregateException ae) { throw ae.InnerException; }
return View(viewModel);
}
这一切都很完美,但我确实有一些担忧。
这是通过在调用原始操作之前设置区域性来扩展操作的正确方法吗?
有人知道将 CurrentUICulture 传递到 ASP.NET MVC 异步操作的后台线程的不同方法吗?
- session 不是一个选项。
- 我确实在考虑使用 CallContext。
对此代码还有其他评论吗?
谢谢
最佳答案
看来问题中描述的方式就是答案。
关于asp.net-mvc - 将 CurrentUICulture 传递给 ASP.NET MVC 3.0 中的异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7511318/