1. 程式人生 > >ASP.NET Core MVC通過IViewLocationExpander擴充套件檢視搜尋路徑

ASP.NET Core MVC通過IViewLocationExpander擴充套件檢視搜尋路徑

**IViewLocationExpander API** - ExpandViewLocations Razor檢視路徑,檢視引擎會搜尋該路徑. - PopulateValues 每次呼叫都會填充路由 專案目錄如下所示 ![](https://imgkr.cn-bj.ufileos.com/432c939c-fe44-47ad-9522-88f612eacf01.png) 建立區域擴充套件器,其實我並不需要多區域,我目前只需要達到一個區域中有多個資料夾進行存放我的檢視. 所以我通過實現**IViewLocationExpander**進行擴充套件新增我自定義檢視路徑規則即可正如下程式碼片段 ```csharp public class MyViewLocationExpander : IViewLocationExpander { public IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable 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 註冊 ```csharp public void ConfigureServices(IServiceCollection services) { services.Configure(o => { o.ViewLocationExpanders.Add(new MyViewLocationExpander()); }); services.AddMvc(); } ``` ```csharp app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapAreaControllerRoute( name: "sysManage", "sysManage", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); }); ``` 最終路由指向的還是 ``` /SysManage/Controller/Ac