asp.net core Theme 中间件

asp.net core中自定义视图引擎,继承接口 IViewLocationExpander

public class ThemeViewLocationExpander : IViewLocationExpander
    {
        public const string ThemeKey = "Theme";
        public void PopulateValues(ViewLocationExpanderContext context)
        {
            string theme = context.ActionContext.HttpContext.Items[ThemeKey].ToString();
            context.Values[ThemeKey] = theme;
        }
        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            string theme;

            if (context.Values.TryGetValue(ThemeKey, out theme))
            {
                viewLocations = new[] 
                {
                    $"/Themes/{theme}/Views/{{1}}/{{0}}.cshtml",
                    $"/Themes/{theme}/Views/Shared/{{0}}.cshtml",
                    $"/Themes/{theme}/Areas/{{2}}/Views/{{1}}/{{0}}.cshtml",
                    $"/Themes/{theme}/Areas/{{2}}/Views/Shared/{{0}}.cshtml",
                }
                .Concat(viewLocations);
            }
            return viewLocations;
        }
    }

新建中间件ThemeMiddleware

public class ThemeMiddleware
    {
        private readonly RequestDelegate _next;
        public IConfiguration _configuration;
        public ThemeMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }
        public Task Invoke(HttpContext context)
        {
            var folder = _configuration.GetSection("theme").Value;
            context.Request.HttpContext.Items[ThemeViewLocationExpander.ThemeKey] = folder ?? "Default";
            return _next(context);
        }
    }

中间件扩展

    public static class MiddlewareExtensions
    {
        /// <summary>
        /// 启用Theme中间件
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseTheme(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ThemeMiddleware>();
        }
    }

中间件服务扩展

public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Theme服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddTheme(this IServiceCollection services)
        {
            return services.Configure<RazorViewEngineOptions>(options => {
                options.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
            });
        }
    }

使用:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddTheme(); //添加Theme服务
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
          

            app.UseTheme();//启用theme中间件
            app.UseMvcWithDefaultRoute();
}