天天看點

ASP.NET Core MVC通過IViewLocationExpander擴充視圖搜尋路徑

ASP.NET Core MVC通過IViewLocationExpander擴充視圖搜尋路徑

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

原文位址

https://www.cnblogs.com/yyfh/p/12636976.html

繼續閱讀