ASP.NET Core自定义View查找路径,实现主题切换

目的:修改视图的查找路径

PopulateValues方法:每次http请求都会执行,

ExpandViewLocations方法:根据context.Values的值缓存执行。相同值,此方法只会执行一次

viewLocations参数:默认查找路径

案例:切换主题

案例中使用Query参数中获取theme,项目中可以改成从配置文件中获取(在中间件中修改,通过HttpContext.Items传递参数)

public class ThemeViewLocationExpander : IViewLocationExpander
    {
        public void PopulateValues(ViewLocationExpanderContext context)
        {
            string theme = context.ActionContext.HttpContext.Request.Query["theme"].ToString();
            context.Values["theme"] = theme;
        }
        //有缓存,context.Values["theme"]相同值只会执行一次此方法
        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            string theme = context.Values["theme"];
            if (string.IsNullOrWhiteSpace(theme))
            {
                theme = "default";
            }
            string[] newLocation = { $"Views/{theme}/{{1}}/{{0}}.cshtml" };//1代表Controller、0代表Action
            return viewLocations.Union(newLocation);
        }

    }

ConfigureServices方法中添加:

//配置模版视图路径
            services.Configure<RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
            });
原文地址:https://www.cnblogs.com/fanfan-90/p/12716694.html