当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径

ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径

2020年04月05日  | 移动技术网IT编程  | 我要评论

陈品亨,船用卫星电视天线,宣花葫芦

iviewlocationexpander api

  • expandviewlocations razor视图路径,视图引擎会搜索该路径.
  • populatevalues 每次调用都会填充路由

项目目录如下所示

创建区域扩展器,其实我并不需要多区域,我目前只需要达到一个区域中有多个文件夹进行存放我的视图.

所以我通过实现iviewlocationexpander进行扩展添加我自定义视图路径规则即可正如下代码片段

 public class myviewlocationexpander : iviewlocationexpander
    {
        public ienumerable<string> expandviewlocations(viewlocationexpandercontext context, ienumerable<string> viewlocations)
        {
            if (context.controllername != null && context.controllername.startswith("app"))
            {
                viewlocations = viewlocations.concat(
                    new[] { $"/areas/sysmanage/views/app/{context.controllername}/{context.viewname}{razorviewengine.viewextension}"
                           });
                return viewlocations;
            }

            if (context.areaname != "sysmanage") return viewlocations;
            viewlocations = viewlocations.concat(
                new[] { $"/areas/sysmanage/views/system/{context.controllername}/{context.viewname}{razorviewengine.viewextension}"
                });
            return viewlocations;
        }

        public void populatevalues(viewlocationexpandercontext context)
        {
        }
    }

在startup.configureservices 注册

  public void configureservices(iservicecollection services)  
        {  
            services.configure<razorviewengineoptions>(o => {  
                o.viewlocationexpanders.add(new myviewlocationexpander());  
            });  
            services.addmvc();  
        } 
 app.useendpoints(endpoints =>
            {
                endpoints.maprazorpages();
                endpoints.mapareacontrollerroute(
                    name: "sysmanage", "sysmanage",
                    pattern: "{area:exists}/{controller=home}/{action=index}/{id?}");
            });

最终路由指向的还是

/sysmanage/controller/action

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网