新建ThemeViewLocationExpander.cs 實現IViewLocationExpander接口blog
/// <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; } } }
添加新的ViewLocationExpanders接口
public class Startup{ public virtual void ConfigureServices(IServiceCollection services) { services.AddMvc().AddRazorOptions(option => { option.ViewLocationExpanders.Clear(); option.ViewLocationExpanders.Add(new ThemeViewLocationExpander()); }) } }