前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径

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

作者头像
HueiFeng
发布2020-04-08 15:39:52
7920
发布2020-04-08 15:39:52
举报
文章被收录于专栏:HueiFeng技术专栏

IViewLocationExpander API

  • ExpandViewLocations Razor视图路径,视图引擎会搜索该路径.
  • PopulateValues 每次调用都会填充路由

项目目录如下所示

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

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

代码语言:javascript
复制
 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 注册

代码语言:javascript
复制
  public void ConfigureServices(IServiceCollection services)  
        {  
            services.Configure<RazorViewEngineOptions>(o => {  
                o.ViewLocationExpanders.Add(new MyViewLocationExpander());  
            });  
            services.AddMvc();  
        } 
代码语言:javascript
复制
 app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapAreaControllerRoute(
                    name: "sysManage", "sysManage",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            });

最终路由指向的还是

代码语言:javascript
复制
/SysManage/Controller/Action
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档