代码之家  ›  专栏  ›  技术社区  ›  Petr Felzmann

ASP.NET核心:以编程方式为本地化视图设置资源文件

  •  0
  • Petr Felzmann  · 技术社区  · 5 年前

    我有一个用ASP.NET Core v2.1编写的web应用程序。该应用程序使用通过配置的本地化视图 LocalizationOptions.ResourcesPath = "Resources" 而对本地化字符串的访问是通过注入的 IViewLocalizer 在cshtml文件中。

    在某些情况下,我希望使用与中的默认资源文件不同的资源文件渲染视图 Resources 文件夹另一个资源文件与默认文件具有相同的键(无需更改视图),因此只呈现不同的文本。

    例如,考虑控制器中的这种动作方法,看看我想解决的问题:

    public async Task<IActionResult> ShowSomething([FromQuery] bool useDifferentResource)
    {
        if (useDifferentResource)
        {
            // how to render the view which will use different resource file
            // then the default found in Resources folder?
            // return View("MyView");
        }
        
        // this renders the view with the default resource file found in Resources folder
        return View("MyView");
    }
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   King King    5 年前

    首先,我不太确定你的要求是否必要。但通过深入研究源代码,我发现这是可能的,并在这里提出了一个解决方案。

    其实 IViewLocalizer IHtmlLocalizerFactory 登记为单身人士。这取决于 IStringLocalizerFactory ResourceManager ResourceManagerStringLocalizerFactory . LocalizationOptions 要获得配置的 ResourcesPath 用于创建的实例 IStringLocalizer HtmlLocalizer 最后裹上 ViewLocalizer . 这里的要点是,结果由缓存键缓存,具体取决于视图/页面路径&程序集的名称(资源嵌入其中)。所以在第一次创建 视图定位器 (通过DI提供),它将被缓存,您没有机会更改配置的 资源量 或者拦截来改变它。

    这意味着我们需要一个定制 ResourceManagerStringLocalizerFactory 覆盖 Create 方法(实际上它不是虚拟的,但我们可以重新实现它)。我们需要在缓存键中包含另外一个因素(运行时资源路径),以便缓存能够正常工作。还有一个虚拟方法 ResourceManagerStringLocalizerFactory 可以重写以提供运行时资源路径的: GetResourceLocationAttribute . 最小化自定义的实现代码 ResourceManagerStringLocalizerFactory

    这是核心原则。然而,当涉及到完整解决方案的实现时,它并没有那么简单。以下是完整的代码:

    /// <summary>
    /// A ViewLocalizer that can be aware of the request feature IActiveViewLocalizerFeature to use instead of 
    /// basing on the default implementation of ViewLocalizer
    /// </summary>
    public class ActiveLocalizerAwareViewLocalizer : ViewLocalizer
    {
        readonly IHttpContextAccessor _httpContextAccessor;
        public ActiveLocalizerAwareViewLocalizer(IHtmlLocalizerFactory localizerFactory, IHostingEnvironment hostingEnvironment,
            IHttpContextAccessor httpContextAccessor) : base(localizerFactory, hostingEnvironment)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        public override LocalizedHtmlString this[string key, params object[] arguments]
        {
            get
            {
                var localizer = _getActiveLocalizer();
                return localizer == null ? base[key, arguments] : localizer[key, arguments];
            }
        }
    
        public override LocalizedHtmlString this[string key]
        {
            get
            {
                var localizer = _getActiveLocalizer();
                return localizer == null ? base[key] : localizer[key];
            }
        }
        IHtmlLocalizer _getActiveLocalizer()
        {
            return _httpContextAccessor.HttpContext.Features.Get<IActiveViewLocalizerFeature>()?.ViewLocalizer;
        }
    }
    
    public static class HtmlLocalizerFactoryWithRuntimeResourcesPathExtensions
    {
        public static T WithResourcesPath<T>(this T factory, string resourcesPath) where T : IHtmlLocalizerFactory
        {
            if (factory is IRuntimeResourcesPath overridableFactory)
            {
                overridableFactory.SetRuntimeResourcesPath(resourcesPath);
            }
            return factory;
        }
    }
    
    public interface IActiveViewLocalizerFeature
    {
        IHtmlLocalizer ViewLocalizer { get; }
    }
    
    public class ActiveViewLocalizerFeature : IActiveViewLocalizerFeature
    {
        public ActiveViewLocalizerFeature(IHtmlLocalizer viewLocalizer)
        {
            ViewLocalizer = viewLocalizer;
        }
        public IHtmlLocalizer ViewLocalizer { get; }
    }
    
    public interface IRuntimeResourcesPath
    {
        string ResourcesPath { get; }
        void SetRuntimeResourcesPath(string resourcesPath);
    }
    
    public class RuntimeResourcesPathHtmlLocalizerFactory : HtmlLocalizerFactory, IRuntimeResourcesPath
    {
        readonly IStringLocalizerFactory _stringLocalizerFactory;
        public RuntimeResourcesPathHtmlLocalizerFactory(IStringLocalizerFactory localizerFactory) : base(localizerFactory)
        {
            _stringLocalizerFactory = localizerFactory;
        }
        //NOTE: the factory is registered as a singleton, so we need this to manage different resource paths used on different tasks
        readonly AsyncLocal<string> _asyncResourcePath = new AsyncLocal<string>();
        public string ResourcesPath => _asyncResourcePath.Value;
    
        void IRuntimeResourcesPath.SetRuntimeResourcesPath(string resourcesPath)
        {
            _asyncResourcePath.Value = resourcesPath;
        }
        public override IHtmlLocalizer Create(string baseName, string location)
        {
            if (_stringLocalizerFactory is IRuntimeResourcesPath overridableFactory)
            {
                overridableFactory.SetRuntimeResourcesPath(ResourcesPath);
            }
            return base.Create(baseName, location);
        }
    }
    
    public static class RuntimeResourcesPathHtmlLocalizerFactoryExtensions
    {
        /// <summary>
        /// Creates an IHtmlLocalizer with a runtime resources path (instead of using the configured ResourcesPath)
        /// </summary>
        public static IHtmlLocalizer CreateWithResourcesPath(this IHtmlLocalizerFactory factory, string resourcesPath, string baseName, string location = null)
        {
            location = location ?? Assembly.GetEntryAssembly().GetName().Name;
            var result = factory.WithResourcesPath(resourcesPath).Create(baseName, location);
            factory.WithResourcesPath(null);
            return result;
        }
    }
    
    public static class RuntimeResourcesPathLocalizationExtensions
    {
        static IHtmlLocalizer _useLocalizer(ActionContext actionContext, string resourcesPath, string viewPath)
        {
            var factory = actionContext.HttpContext.RequestServices.GetRequiredService<IHtmlLocalizerFactory>();
    
            viewPath = viewPath.Substring(0, viewPath.Length - Path.GetExtension(viewPath).Length).TrimStart('/', '\\')
                       .Replace("/", ".").Replace("\\", ".");
    
            var location = Assembly.GetEntryAssembly().GetName().Name;
    
            var localizer = factory.CreateWithResourcesPath(resourcesPath, viewPath, location);
            actionContext.HttpContext.Features.Set<IActiveViewLocalizerFeature>(new ActiveViewLocalizerFeature(localizer));
            return localizer;
        }
        /// <summary>
        /// Can be used inside Controller
        /// </summary>
        public static IHtmlLocalizer UseLocalizer(this ActionContext actionContext, string resourcesPath, string viewOrPageName = null)
        {
            //find the view before getting the path
            var razorViewEngine = actionContext.HttpContext.RequestServices.GetRequiredService<IRazorViewEngine>();
            if (actionContext is ControllerContext cc)
            {
                viewOrPageName = viewOrPageName ?? cc.ActionDescriptor.ActionName;
                var viewResult = razorViewEngine.FindView(actionContext, viewOrPageName, false);
                return _useLocalizer(actionContext, resourcesPath, viewResult.View.Path);
            }
            var pageResult = razorViewEngine.FindPage(actionContext, viewOrPageName);
            //NOTE: here we have pageResult.Page is an IRazorPage but we don't use that to call UseLocalizer
            //because that IRazorPage instance has very less info (lacking ViewContext, PageContext ...)
            //The only precious info we have here is the Page.Path
            return _useLocalizer(actionContext, resourcesPath, pageResult.Page.Path);
        }
        /// <summary>
        /// Can be used inside Razor View or Razor Page
        /// </summary>
        public static IHtmlLocalizer UseLocalizer(this IRazorPage razorPage, string resourcesPath)
        {
            var path = razorPage.ViewContext.ExecutingFilePath;
            if (string.IsNullOrEmpty(path))
            {
                path = razorPage.ViewContext.View.Path;
            }
            if (path == null) return null;
            return _useLocalizer(razorPage.ViewContext, resourcesPath, path);
        }
        /// <summary>
        /// Can be used inside PageModel
        /// </summary>
        public static IHtmlLocalizer UseLocalizer(this PageModel pageModel, string resourcesPath)
        {
            return pageModel.PageContext.UseLocalizer(resourcesPath, pageModel.RouteData.Values["page"]?.ToString()?.TrimStart('/'));
        }
    }
    

    ResourceManagerStringLocalizerFactory

    public class RuntimeResourcesPathResourceManagerStringLocalizerFactory 
        : ResourceManagerStringLocalizerFactory, IRuntimeResourcesPath, IStringLocalizerFactory
    {
        readonly AsyncLocal<string> _asyncResourcePath = new AsyncLocal<string>();
        public string ResourcesPath => _asyncResourcePath.Value;
        private readonly ConcurrentDictionary<string, ResourceManagerStringLocalizer> _localizerCache =
            new ConcurrentDictionary<string, ResourceManagerStringLocalizer>();
    
        public RuntimeResourcesPathResourceManagerStringLocalizerFactory(IOptions<LocalizationOptions> localizationOptions, ILoggerFactory loggerFactory) : base(localizationOptions, loggerFactory)
        {
        }
        protected override ResourceLocationAttribute GetResourceLocationAttribute(Assembly assembly)
        {
            //we is where we override the configured ResourcesPath and use the runtime ResourcesPath.
            return ResourcesPath == null ? base.GetResourceLocationAttribute(assembly) : new ResourceLocationAttribute(ResourcesPath);
        }        
    
        public void SetRuntimeResourcesPath(string resourcesPath)
        {
            _asyncResourcePath.Value = resourcesPath;
        }
        /// <summary>
        /// Almost cloned from the source code of ResourceManagerStringLocalizerFactory
        /// We need to re-implement this because the framework code caches the result of Create using a cache key depending on only baseName & location.
        /// But here we introduce one more parameter of (runtime) ResourcesPath, so we need to include that in the cache key as well for 
        /// it to work properly (otherwise each time changing the runtime ResourcesPath, the same cached result will be returned, which is wrong).
        /// </summary>        
        IStringLocalizer IStringLocalizerFactory.Create(string baseName, string location)
        {
            if (baseName == null)
            {
                throw new ArgumentNullException(nameof(baseName));
            }
    
            if (location == null)
            {
                throw new ArgumentNullException(nameof(location));
            }
    
            return _localizerCache.GetOrAdd($"B={baseName},L={location},R={ResourcesPath}", _ =>
            {
                var assemblyName = new AssemblyName(location);
                var assembly = Assembly.Load(assemblyName);
                baseName = GetResourcePrefix(baseName, location);
    
                return CreateResourceManagerStringLocalizer(assembly, baseName);
            });
        }
    }
    

    public static class RuntimeResourcesPathLocalizationServiceCollectionExtensions
    {
        public static IServiceCollection AddRuntimeResourcesPathForLocalization(this IServiceCollection services)
        {
            services.AddSingleton<IStringLocalizerFactory, RuntimeResourcesPathResourceManagerStringLocalizerFactory>();
            services.AddSingleton<IHtmlLocalizerFactory, RuntimeResourcesPathHtmlLocalizerFactory>();
            return services.AddSingleton<IViewLocalizer, ActiveLocalizerAwareViewLocalizer>();
        }
    }
    

    我们实现了一个定制 IVEWLLOCALizer 这样它就可以无缝地用于您的代码中。它的工作只是检查是否有任何活动的 IHtmlLocalizer HttpContext (作为一个称为 IActiveViewLocalizerFeature . 每个不同的运行时资源路径将创建不同的 将作为活动定位器共享。通常在一个请求范围内(以及在视图上下文中),我们通常只需要使用一个运行时资源路径(在呈现视图之前的最开始处指定)。

    要注册自定义服务,请执行以下操作:

    services.AddRuntimeResourcesPathForLocalization();
    

    要将定位器与运行时资源路径一起使用,请执行以下操作:

    public async Task<IActionResult> ShowSomething([FromQuery] bool useDifferentResource)
    {
      if (useDifferentResource)
      {
         this.UseLocalizer("resources path of your choice");
      }
        
      return View("MyView");
    }
    

    笔记 字体 UseLocalizer 在控制器或页面模型的作用域内,由于查找视图/页面的额外逻辑(使用 IRazorViewEngine 使用定位器 到 RazorPage 或 View

    推荐文章