欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-28 18:49:22
IViewLocationExpander API ExpandViewLocations Razor视图路径,视图引擎会搜索该路径. PopulateValues 每次调用都会填充路由 项目目录如下所示 创建区域扩展器,其实我并不需要多区域,我目前只需要达到一个区域中有多个文件夹进行存放我的视图. ......

iviewlocationexpander api

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

项目目录如下所示

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

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

所以我通过实现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