ASP.NET Core自定义View查找路径,实现主题切换(IViewLocationExpander)
目的:修改视图的查找路径
PopulateValues方法:每次http请求都会执行
ExpandViewLocations方法:根据context.Values的值缓存执行。相同值,此方法只会执行一次
viewLocations参数:默认查找路径
方案1:
案例中使用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" };//2代表Area、1代表Controller、0代表Action
return viewLocations.Union(newLocation);
}
}
ConfigureServices方法中添加:
//配置模版视图路径
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
});
方案2
services.Configure<RazorViewEngineOptions>(options =>
{
////第二种定位自定义页面文件的位置
//options.AreaViewLocationFormats.Clear();
//options.AreaViewLocationFormats.Add("/Areas/{2}/Views/{1}/{0}.cshtml");
//options.AreaViewLocationFormats.Add("/Areas/{2}/Views/Shared/{0}.cshtml");
//options.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
});