首页 > 解决方案 > 如何指定自定义位置(绝对路径)以在 asp.net core mvc 中加载区域?

问题描述

我正在尝试通过指定绝对路径 (C:/WebApplication7/MS/{2}/Views/{1}/{0}.cshtml)从自定义目录加载区域。我尝试在Startup.cs中指定AreaLocationFormats并实现IViewLocationExpander。当我提供相对路径 (/MS/{2}/Views/{1}/{0}.cshtml)时,这两个都可以正常工作,但我需要通过提供目录的确切路径来加载视图,因为我的视图将存在于单独的目录中。这在某种程度上可能吗?

services.AddControllersWithViews()
                 .AddRazorOptions(options =>
                 {
                     options.AreaViewLocationFormats.Add(@"/MS/{2}/Views/{1}/{0}.cshtml");
                 });
 services.AddControllersWithViews()
                 .AddRazorOptions(options =>
                 {
                     options.ViewLocationExpanders.Add(new ViewLocationExpander());
                 });

public class ViewLocationExpander : IViewLocationExpander
    {
        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            //{2} is area, {1} is controller,{0} is the action
            string[] locations = new string[] { "/MS/{2}/Views/{1}/{0}.cshtml" };
            return locations.Union(viewLocations);          //Add mvc default locations after ours
        }

        public void PopulateValues(ViewLocationExpanderContext context)
        {
            context.Values["customviewlocation"] = nameof(ViewLocationExpander);
        }
    }

标签: c#model-view-controllerasp.net-core-mvcasp.net-core-3.1

解决方案


通过更多的研究,我能够通过配置一个新的FileProvider来做到这一点

安装Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation nuget 包和 Startup.cs 中的行

services.Configure<MvcRazorRuntimeCompilationOptions>(options => {
    options.FileProviders.Add(new PhysicalFileProvider(@"C:/WebApplication7"));
});

有关配置文件提供程序的详细信息:https ://github.com/dotnet/AspNetCore.Docs/issues/14593

使用 FileProvider 定义上述两种方法都可以正常工作。


推荐阅读