asp.net core Theme 中介軟體
阿新 • • 發佈:2018-11-05
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(); }