我一直在尝试关注在此处找到的博客文章。我添加了一个新程序集来托管我的资源文件(我使用了一个单独的程序集,因为资源可能需要在多个项目之间共享)。我在 web.config 中添加了以下内容:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="MyResources.Resources"/> <!-- New entry for resources -->
</namespaces>
</pages>
</system.web.webPages.razor>
我已经为测试目的添加了资源字符串到一些文件中。现在我似乎遇到的问题是我无法将资源设置为默认值以外的任何内容。例如,在生成的资源文件设计器中有以下内容:
/// <summary>
/// Looks up a localized string similar to Log in was unsuccessful. Please correct the errors and try again..
/// </summary>
public static string Account_LoginUnsuccessful {
get {
return ResourceManager.GetString("Account_LoginUnsuccessful", resourceCulture);
}
}
如果我在此方法中设置断点,resourceCulture
则除了 null 之外什么都没有。即使我尝试了以下方法:
在 Global.asax.ca 中:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
var culture = new System.Globalization.CultureInfo("fr");
// Modify current thread's cultures
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture.Name);
} // End of Application_AcquireRequestState
在我所有其他控制器都继承的基本 mvc 控制器中:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
SetCulture(requestContext.HttpContext.Request);
base.Initialize(requestContext);
}
protected override void ExecuteCore()
{
SetCulture(Request);
base.ExecuteCore();
}
protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
SetCulture(requestContext.HttpContext.Request);
base.Execute(requestContext);
}
protected override IAsyncResult BeginExecute(System.Web.Routing.RequestContext requestContext, AsyncCallback callback, object state)
{
SetCulture(requestContext.HttpContext.Request);
metrics = Metrics.BeginTimer();
return base.BeginExecute(requestContext, callback, state);
}
private void SetCulture(HttpRequestBase Request)
{
string cultureName = "fr";
// Validate culture name
cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
现在,据我了解,设置线程当前文化应该会导致我的资源文件文化发生变化。我似乎无法在我的生活中得到这样的工作(因此我尝试在大约十个不同的地方设置文化)。
关于我在这里做错了什么有什么建议吗?