在mvc中使用IViewLocationExpander
我想从自定义位置渲染视图,所以为此我在类中实现了IViewLocationExpander
接口。 我在startup file
注册了相同的类,如下所示。
Startup.cs文件
public void ConfigureServices(IServiceCollection services) { ..... //Render view from custom location. services.Configure(options => { options.ViewLocationExpanders.Add(new CustomViewLocationExpander()); }); .... }
CustomViewLocationExpander类
public class CustomViewLocationExpander : IViewLocationExpander { public IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations) { var session = context.ActionContext.HttpContext.RequestServices.GetRequiredService(); string folderName = session.GetSession("ApplicationType"); viewLocations = viewLocations.Select(f => f.Replace("/Views/", "/" + folderName + "/")); return viewLocations; } public void PopulateValues(ViewLocationExpanderContext context) { } }
我的应用程序视图结构如下
我的问题是,如果我从URL http:// localhost:56739 / trainee / Login / myclientname访问ViewsFrontend
文件夹中的Views / Login视图,并立即将浏览器中的url更改为http:// localhost:56739 / admin / Login / myclientname ,然后在这种情况下它仍然引用ViewsFrontend
文件夹,它应该引用ViewsBackend
文件夹。
与受训者的Url应该引用ViewsFrontend
文件夹,而admin应该引用ViewsBackend
文件夹。
在浏览器中更改url后,它只调用PopulateValues
方法,但不调用ExpandViewLocations
方法。
那么如何重新配置这个类来为其他文件夹工作呢?
谢谢您的帮助 !
PopulateValues
作为一种指定参数的方式存在,您的视图查找将根据每个请求而变化。 由于您没有填充它,因此视图引擎使用先前请求中的缓存值。 将应用程序类型添加到PopulateValues并调用ExpandValues:
public class CustomViewLocationExpander : IViewLocationExpander { public IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable 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(); string applicationType = session.GetSession("ApplicationType"); context.Values["ApplicationType"] = applicationType; } }
如果你试图让Razor从另一个位置找到视图,我过去曾使用过这种技术 。 ReSharper也很聪明,可以接受。
- 使用ASP .NET Core Identity和EntityFrameworkCore注册新用户时出现InvalidOperationException
- asp.net mvc core以下方法或属性之间的调用不明确:
- 在dotnet核心中运行NUnit测试
- 如何在ASP.NET Core 1.0的DI中的Startup类中添加IHttpContextAccessor?
- ASP.NET CORE 1.0,模拟
- error handling(将ex.Message发送到客户端)
- 使用Identity 2.0数据库来validationASP.NET Core 1.0应用程序
- 在完整的.NET框架上测试Asp.Net Core
- 在.NET Core中使用DataTable