当前位置:网站首页>asp. Net core theme Middleware
asp. Net core theme Middleware
2022-06-12 04:41:00 【Wind god Shura envoy】
asp.net core Custom view engine in , Inherited interface 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;
}
}
New middleware 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);
}
}
Middleware extensions
public static class MiddlewareExtensions
{
/// <summary>
/// Enable Theme middleware
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseTheme(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ThemeMiddleware>();
}
}
Middleware service extensions
public static class ServiceCollectionExtensions
{
/// <summary>
/// add to Theme service
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddTheme(this IServiceCollection services)
{
return services.Configure<RazorViewEngineOptions>(options => {
options.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
});
}
}
Use :
public void ConfigureServices(IServiceCollection services)
{
services.AddTheme(); // add to Theme service
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseTheme();// Enable theme middleware
app.UseMvcWithDefaultRoute();
}
C# - stay MVC Use in IViewLocationExpander
I want to render from a custom location View , So I have achieved
Class IViewLocationExpander Interface (interface). I am already in Startup Class is registered with the same class , As shown below .
Startup class
public void ConfigureServices(IServiceCollection services)
{
…
//Render view from custom location.
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new CustomViewLocationExpander());
});
…
}
CustomViewLocationExpander class
public class CustomViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
var session = context.ActionContext.HttpContext.RequestServices.GetRequiredService<SessionServices>();
string folderName = session.GetSession<string>("ApplicationType");
viewLocations = viewLocations.Select(f => f.Replace("/Views/", "/" + folderName + "/"));
return viewLocations;
}
public void PopulateValues(ViewLocationExpanderContext context)
{
}
}
Last , Of my application View Is organized as follows :
My question : If I start from the following URL from Views/Login Folder Access ViewsFrontend View :
http://localhost:56739/trainee/Login/myclientname
But then immediately put... In the browser URL Change to :
http://localhost:56739/admin/Login/myclientname
under these circumstances , Even now it should now reference ViewsFrontend Folder , It still references ViewsBackend Folder , Because in order to trainee At the beginning URL You should quote ViewsFrontend Folder , And then admin At the beginning URL You should quote ViewsBackend Folder .
Besides , Change... In the browser URL after , It just calls PopulateValues() Method , Instead of calling ExpandViewLocations() Method .
How do I reconfigure This class makes it available to other folders ?
The best answer
PopulateValues Is a method for specifying parameters , Your View The lookup will vary according to each request . Because it is not filled , therefore View The engine will use the cached value from the previous request .
To solve this problem , Please send your ApplicationType Variable added to PopulateValues() In the method , And as long as the value changes , You should call ExpandValues() Method :
public class CustomViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
string folderName = context.Values["ApplicationType"];
viewLocations = viewLocations.Select(f => f.Replace("/Views/", "/" + folderName + "/"));
return viewLocations;
}
public void PopulateValues(ViewLocationExpanderContext context)
{
var session = context.ActionContext.HttpContext.RequestServices.GetRequiredService<SessionServices>();
string applicationType = session.GetSession<string>("ApplicationType");
context.Values["ApplicationType"] = applicationType;
}
}
边栏推荐
- [SC] OpenService FAILED 5: Access is denied.
- Exception handling and unit testing
- LabVIEW about TDMS and Binary Storage Speed
- Notes on relevant knowledge points such as original code / inverse code / complement code, size end, etc
- Why should a redis cluster use a reverse proxy? Just read this one
- JWT学习与使用
- Manually encapsulate a foreacht and map
- Understanding of day16 array create query static and dynamic array array array performance in memory
- According to aiqicha, keep went public in Hong Kong and hit the "first share of online fitness"
- Call reminder
猜你喜欢

分布式锁介绍

kali_ Nat mode, bridging Internet / host only_ detailed

Day17 array features array boundary array application traversal array multidimensional array creation and traversal arrays operation array bubble sort

Ubunt 20.04 uses CDROM or ISO as the installation source

2022 electrician (elementary) operation certificate examination question bank and online simulation examination

Using datetime in MySQL

Kill session? This cross domain authentication solution is really elegant!

MFC General dialog color dialog

命令执行漏洞详解

Bearpi IOT serial port transceiver 1- normal mode
随机推荐
Unable to resolve dependency tree
疫情数据分析平台工作报告【6】可视化绘图
@What happens if bean and @component are used on the same class?
Bearpi IOT serial port transceiver 1- normal mode
[SC] OpenService FAILED 5: Access is denied.
Simple Tetris
树莓派4B使用Intel Movidius NCS 2来进行推断加速
QT experiment - gold coin flipping games
2022 examination questions and simulation examination for crane driver (limited to bridge crane)
Bearpi IOT lighting LED
Summary of common interview questions in redis
如何制作数据集并基于yolov5训练成模型并部署
Illustrating the use of Apache skywalking UI
AI and logistics Patent
Understanding of day16 array create query static and dynamic array array array performance in memory
JWT learning and use
eBPF系列学习(4)了解libbpf、CO-RE (Compile Once – Run Everywhe) | 使用go开发ebpf程序(云原生利器cilium ebpf )
Question for the 3D printing lattice?
Based on Visual Studio code Net Maui cross platform mobile application development
Construction case of Expressway Precast Beam Yard (with scheme text)