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();
}
本文介绍了如何在ASP.NET Core中创建自定义视图引擎,通过继承IViewLocationExpander接口,并实现`ThemeViewLocationExpander`,结合配置中间件`ThemeMiddleware`和扩展方法,实现实时主题切换。同时展示了如何在`ConfigureServices`和`Configure`方法中集成这些组件。
1083

被折叠的 条评论
为什么被折叠?



