在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
之前MVC5和之前的版本中,我们要想对View文件的路径进行控制的话,则必须要对 通过RazorViewEngine来控制View路径 在新版的 public class ThemeViewEngine : RazorViewEngine { public ThemeViewEngine(IRazorPageFactory pageFactory, IRazorViewFactory viewFactory, IViewLocationExpanderProvider viewLocationExpanderProvider, IViewLocationCache viewLocationCache) : base(pageFactory, viewFactory, viewLocationExpanderProvider, viewLocationCache) { } public override IEnumerable<string> AreaViewLocationFormats { get { var value = new Random().Next(0, 1); var theme = value == 0 ? "Theme1" : "Theme2"; // 可通过其它条件,设置皮肤的种类 return base.AreaViewLocationFormats.Select(f => f.Replace("/Views/", "/Views/" + theme + "/")); } } public override IEnumerable<string> ViewLocationFormats { get { var value = new Random().Next(0, 1); var theme = value == 0 ? "Theme1" : "Theme2"; // 可通过其它条件,设置皮肤的种类 return base.ViewLocationFormats.Select(f => f.Replace("/Views/", "/Views/" + theme + "/")); } } } 然后,通过修改MVcOptions的实例属性ViewEngines即可完成对视图引擎的替换,代码如下: services.AddMvc().Configure<MvcOptions>(options => { options.ViewEngines.Clear(); options.ViewEngines.Add(typeof(ThemeViewEngine)); }); 这样,系统在查找视图文件的时候,就会按照新注册的 通过IViewLocationExpander来控制View路径 在MVC6中,微软还提供了另外一种新的方式来控制View文件的路径,那就是 public class ThemeViewLocationExpander : IViewLocationExpander { public void PopulateValues(ViewLocationExpanderContext context) { var value = new Random().Next(0, 1); var theme = value == 0 ? "Theme1" : "Theme2"; context.Values["theme"] = theme; } public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { return viewLocations.Select(f => f.Replace("/Views/", "/Views/" + context.Values["theme"] + "/")); } } 在上述自定义的 最后,我们在 services.Configure<RazorViewEngineOptions>(options => { options.ViewLocationExpanders.Add(typeof(ThemViewLocationExpander)); }); |
请发表评论