加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在mvc中使用IViewLocationExpander

发布时间:2020-12-15 23:35:23 所属栏目:百科 来源:网络整理
导读:我想从自定义位置渲染视图,所以我已经实现了 类中的IViewLocationExpander接口.我在启动文件中注册了相同的类,如下所示. Startup.cs文件 public void ConfigureServices(IServiceCollection services) { ..... //Render view from custom location. services
我想从自定义位置渲染视图,所以我已经实现了
类中的IViewLocationExpander接口.我在启动文件中注册了相同的类,如下所示.

Startup.cs文件

public void ConfigureServices(IServiceCollection services)
    {
       .....
        //Render view from custom location.
        services.Configure<RazorViewEngineOptions>(options =>
        {
            options.ViewLocationExpanders.Add(new CustomViewLocationExpander());
        });
        ....
    }

CustomViewLocationExpander类

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)
    {

    }
}

我的应用程序视图结构如下

enter image description here

我的问题是如果我从URL访问ViewsFrontend文件夹中的Views / Login视图
http://localhost:56739/trainee/Login/myclientname并立即将浏览器中的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<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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读