刚接触.core 想自定义ViewEngine 加载不同的视图 但是没找到相应的地方修改 以前mvc4的时候 是继承 razorViewEngine就可以解决问题 现在试了一下 不行 请教一下知道的同学 谢谢
参考 Custom View Engine in ASP.NET Core and MVC 6 with Dynamic View Location :
public class MyRazorViewEngine : RazorViewEngine
{
public MyRazorViewEngine(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 + "/"));
}
}
}
services.AddMvc().Configure<MvcOptions>(options =>
{
options.ViewEngines.Clear();
options.ViewEngines.Add(typeof(MyRazorViewEngine));
});
谢谢 站长达人 我去反编译过 razorViewEngine 却没发现 可以重写的方法
在.net core 2.0 AreaViewLocationFormats和ViewLocationFormats 这两个方法都不是虚方法,怎么解决。
/// <summary>
/// 自定视图主题 实现IViewLocationExpander接口
/// </summary>
public class ThemeViewLocationExpander : IViewLocationExpander
{
public ThemeViewLocationExpander()
{
}
/// <summary>
/// 主题名称
/// /Views/+ViewLocationExpanders
/// </summary>
public string ThemeName { get; set; } = "Default";
public void PopulateValues([FromServices]ViewLocationExpanderContext context)
{
HttpContext httpcontext = context.ActionContext.HttpContext;
string theme = httpcontext.Request.GetTheme();
if (theme.IsNotNullOrEmpty())
{
ThemeName = theme;
}
context.Values["theme"] = ThemeName;
}
/// <summary>
/// 主题切换
/// </summary>
/// <param name="theme"></param>
/// <returns></returns>
public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
IEnumerable<string> viewLocations)
{
string n = string.Empty;
foreach (string item in viewLocations)
{
n = item.ToLower();
if (!n.Contains("/shared"))
{
n = n.Replace("{1}", $"theme/{context.Values["theme"]}/{{1}}");
}
yield return n;
}
}
}
services.AddMvc.AddRazorOptions(option =>
{
option.ViewLocationExpanders.Clear();
option.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
})