【发布时间】:2015-12-21 04:56:52
【问题描述】:
我有一个 HTTP 处理程序,它读取 ASP.NET MVC 程序集中的所有资源文件并将它们转换为 Javascript 对象。除了 1 个相当大的细节之外,代码运行良好,因为我需要能够预定义文化。我不能使用有用的网络配置的自动 UI 文化,而是我想使用数据库配置。这段代码运行后,它仍然会采用我计算机的本地文化。有没有办法设置文化?我正在考虑使用 ResourceManager,但我没有这样做。
public void ProcessRequest(HttpContext context)
{
// Check current assembly
Assembly currentAssembly = null;
Type appType = HttpContext.Current.ApplicationInstance.GetType();
if (appType.Namespace == "ASP")
{
currentAssembly = appType.BaseType.Assembly;
}
else
{
currentAssembly = appType.Assembly;
}
// Get resource files in this assembly, in this cased reference by Resources namespace
IEnumerable<Type> resources = currentAssembly.GetTypes().Where(x => x.Namespace == "Resources");
// Generate Javascript namespace through which each resource file will be referenced
context.Response.ContentType = "text/javascript";
context.Response.Write("var Resources = {};\n");
foreach (Type resource in resources)
{
// For each type, add an object to the namespace
context.Response.Write(string.Format("Resources.{0} = {{}};\n", resource.Name));
// Get all resource keys and values for every resource file
IDictionary<String, String> resourceKeyValues =
resource
.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.GetProperty)
.Where(x => x.PropertyType == typeof(string))
.ToDictionary(x => x.Name, x => x.GetValue(null, null).ToString());
// Include each key + value
foreach (String key in resourceKeyValues.Keys)
{
context.Response.Write(string.Format("Resources.{0}.{1} = '{2}';\n", resource.Name, key, resourceKeyValues[key].Replace("'", "\'")));
}
}
}
【问题讨论】:
标签: asp.net-mvc localization internationalization httphandler