【问题标题】:Javascript files in "feature folders/slices" Aspnet Core“功能文件夹/切片”Aspnet Core 中的 Javascript 文件
【发布时间】:2020-02-25 09:07:04
【问题描述】:

我想为我的 aspnet 核心 MVC 应用程序调整功能文件夹/切片。

我已经设法从 features 文件夹中服务器控制器和 cshtml 文件。

使用此代码...

using Microsoft.AspNetCore.Mvc.Razor;
using System.Collections.Generic;

namespace MyApp.Web
{
    public class FeatureFolderViewLocationExpander : IViewLocationExpander
    {
        public void PopulateValues(ViewLocationExpanderContext context)
        {
            /* no-op */
        }

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            // {0} - Action Name
            // {1} - Controller Name
            // {2} - Area name

            object area;
            if (context.ActionContext.RouteData.Values.TryGetValue("area", out area))
            {
                yield return "/Areas/{2}/{1}/{0}.cshtml";
                yield return "/Areas/{2}/Shared/{0}.cshtml";
                yield return "/Areas/Shared/{0}.cshtml";
            }
            else
            {
                yield return "/Features/{1}/{0}.cshtml";
                yield return "/Features/Shared/{0}.cshtml";
            }
        }
    }
}

和..

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.Configure<RazorViewEngineOptions>(options =>
    {
        options.ViewLocationExpanders.Add(new FeatureFolderViewLocationExpander());
    });
}

...但我还没有设法从 features 文件夹中提供 .js 文件(例如,我上面的解决方案中的 home.js)。

有可能吗?

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    如果你想在 web root 之外访问静态文件,你可以配置静态文件中间件如下:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...
    
            app.UseStaticFiles();//For the wwwroot folder
    
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "Features")),
                RequestPath = "/Features"
            });
    
            ...
        }
    

    然后通过下面的路径访问它

    <script src="~/Features/Home/home.js"></script>
    

    参考:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

    【讨论】:

    • 您是最棒的!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2017-10-07
    • 2017-08-10
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多