以下资源文件的最佳用法是什么?
我也想知道asp.net mvc应用程序中(1)和(2)之间的区别。
答案 0 :(得分:32)
您应该避免App_GlobalResources
和App_LocalResources
。
与Craig提到的一样,App_GlobalResources
/ App_LocalResources
存在问题,因为您无法在ASP.NET运行时之外访问它们。一个很好的例子就是当你对应用程序进行单元测试时,这会产生什么问题。
ķ。斯科特艾伦不久前在博客上写过这篇文章。他在ASP.NET MVC here中用App_GlobalResources
解释问题做得很好。
答案 1 :(得分:12)
如果你选择推荐的解决方案(1)(即在K. Scott Allen的博客中):
对于那些试图使用显式本地化表达式(也称为声明性资源绑定表达式)的人,例如<%$ Resources, MyResource:SomeString %>
public class AppResourceProvider : IResourceProvider
{
private readonly string _ResourceClassName;
ResourceManager _ResourceManager = null;
public AppResourceProvider(string className)
{
_ResourceClassName = className;
}
public object GetObject(string resourceKey, System.Globalization.CultureInfo culture)
{
EnsureResourceManager();
if (culture == null)
{
culture = CultureInfo.CurrentUICulture;
}
return _ResourceManager.GetObject(resourceKey, culture);
}
public System.Resources.IResourceReader ResourceReader
{
get
{
// Not needed for global resources
throw new NotSupportedException();
}
}
private void EnsureResourceManager()
{
var assembly = typeof(Resources.ResourceInAppToGetAssembly).Assembly;
String resourceFullName = String.Format("{0}.Resources.{1}", assembly.GetName().Name, _ResourceClassName);
_ResourceManager = new global::System.Resources.ResourceManager(resourceFullName, assembly);
_ResourceManager.IgnoreCase = true;
}
}
public class AppResourceProviderFactory : ResourceProviderFactory
{
// Thank you, .NET, for providing no way to override global resource providing w/o also overriding local resource providing
private static Type ResXProviderType = typeof(ResourceProviderFactory).Assembly.GetType("System.Web.Compilation.ResXResourceProviderFactory");
ResourceProviderFactory _DefaultFactory;
public AppResourceProviderFactory()
{
_DefaultFactory = (ResourceProviderFactory)Activator.CreateInstance(ResXProviderType);
}
public override IResourceProvider CreateGlobalResourceProvider(string classKey)
{
return new AppResourceProvider(classKey);
}
public override IResourceProvider CreateLocalResourceProvider(string virtualPath)
{
return _DefaultFactory.CreateLocalResourceProvider(virtualPath);
}
}
然后,将其添加到您的web.config:
<globalization requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="utf-8" culture="en-US" uiCulture="en"
resourceProviderFactoryType="Vendalism.ResourceProvider.AppResourceProviderFactory" />
答案 2 :(得分:7)
属性→可以在视图之外查看资源,编译应用程序时会生成强类型。
在编译视图时,ASP.NET会编译App_ *。它们仅在视图中可用。有关全局与本地的信息,请参阅this page。