首页 文章

在ASP.NET Core MVC中提供一些静态文件的问题

提问于
浏览
6

我遇到ASP.NET Core无法正常提供静态文件的问题 . 我的部分应用程序位于wwwroot下的node_modules中 . 在大多数情况下,所有文件都有效,但也有例外 . * .js.map文件被路由到MVC控制器,为我的MVC页面而不是实际文件提供服务 . 结果,我在浏览器中收到错误,例如

无法解析SourceMap:http:// localhost:5000 / node_modules / bootstrap / bootstrap.min.css.map

走同样的路线,我的网络字体,例如包含Bootstrap的网络字体也没有正确提供,也由MVC中间件而不是静态文件中间件处理 . 似乎所有驻留在node_modules中的文件都应该路由到我的静态文件中间件,而这种情况并没有发生 . 谢谢 .

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.WebRootPath, @"node_modules")),
                RequestPath = new PathString("/node_modules"),
                ServeUnknownFileTypes = true

            });

            app.UseMvc(config =>
            {

                config.MapRoute("Default", "{controller}/{action}/{id?}",
                    new { controller = "Home", action = "Index" });

                config.MapRoute("AngularDeepLinkingRoute", "{*url}",
                    new { controller = "Home", action = "Index" });
            });
        }

2 回答

  • 0

    问题是如果缺少静态文件,例如* .js.map文件,静态文件中间件不会处理请求,而是转到MVC中间件 .

  • 1

    删除以下代码,根本不需要

    app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.WebRootPath, @"node_modules")),
                RequestPath = new PathString("/node_modules"),
                ServeUnknownFileTypes = true
    
            });
    

    仅使用以下代码

    app.UseStaticFiles();
    

    如果node_module目录位于wwwroot目录下,则node_module中的内容将被视为静态内容 . 静态文件存储在项目的Web根目录中 . 默认目录是/ wwwroot .

    有关详细信息,请参阅以下链接Microsoft Docs - Working with static files

相关问题