【问题标题】:CSS, Images, JS not loading asp.net Core :(CSS、图像、JS 未加载 asp.net Core :(
【发布时间】:2017-10-30 08:21:39
【问题描述】:

这是我的第一个 .net Core 应用程序。并且有问题。问题是我正在向现有应用程序添加新模板,并且 Google 控制台显示无法找到 CSS 和 JS 的错误

**

  • Appsetting.Json

**

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=MusicSite;Trusted_Connection=True;MultipleActiveResultSets=true"



  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

    "dependencies": {
      "bootstrap": "3.3.6",
      "jquery": "2.2.0"
    }

  }

所有的 CSS 和 Js 文件夹都包含在解决方案中

我在控制台应用程序中遇到的错误

**

  • 控制台错误

**

**

  • 布局页面

**

      <!-- style -->
        <link rel="stylesheet" href="css/animate.css/animate.min.css" type="text/css" />
        <link rel="stylesheet" href="css/glyphicons/glyphicons.css" type="text/css" />
        <link rel="stylesheet" href="css/font-awesome/css/font-awesome.min.css" type="text/css" />
        <link rel="stylesheet" href="css/material-design-icons/material-design-icons.css" type="text/css" />
        <link rel="stylesheet" href="css/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
        <!-- build:css css/styles/app.min.css -->
        <link rel="stylesheet" href="css/styles/app.css" type="text/css" />
        <link rel="stylesheet" href="css/styles/style.css" type="text/css" />
        <link rel="stylesheet" href="css/styles/font.css" type="text/css" />

        <link rel="stylesheet" href="libs/owl.carousel/dist/assets/owl.carousel.min.css" type="text/css" />
        <link rel="stylesheet" href="libs/owl.carousel/dist/assets/owl.theme.css" type="text/css" />
        <link rel="stylesheet" href="libs/mediaelement/build/mediaelementplayer.min.css" type="text/css" />
        <link rel="stylesheet" href="libs/mediaelement/build/mep.css" type="text/css" />
        <!-- endbuild -->

  <script src="libs/jquery/dist/jquery.js"></script>
    <!-- Bootstrap -->
    <script src="libs/tether/dist/js/tether.min.js"></script>
    <script src="libs/bootstrap/dist/js/bootstrap.js"></script>
    <!-- core -->
    <script src="libs/jQuery-Storage-API/jquery.storageapi.min.js"></script>
    <script src="libs/jquery.stellar/jquery.stellar.min.js"></script>
    <script src="libs/owl.carousel/dist/owl.carousel.min.js"></script>
    <script src="libs/jscroll/jquery.jscroll.min.js"></script>
    <script src="libs/PACE/pace.min.js"></script>
    <script src="libs/jquery-pjax/jquery.pjax.js"></script>
    <script src="libs/mediaelement/build/mediaelement-and-player.min.js"></script>
    <script src="libs/mediaelement/build/mep.js"></script>
    <script src="scripts/player.js"></script>
    <script src="scripts/config.lazyload.js"></script>
    <script src="scripts/ui-load.js"></script>
    <script src="scripts/ui-jp.js"></script>
    <script src="scripts/ui-include.js"></script>
    <script src="scripts/ui-device.js"></script>
    <script src="scripts/ui-form.js"></script>
    <script src="scripts/ui-nav.js"></script>
    <script src="scripts/ui-screenfull.js"></script>
    <script src="scripts/ui-scroll-to.js"></script>
    <script src="scripts/ui-toggle-class.js"></script>
    <script src="scripts/ui-taburl.js"></script>
    <script src="scripts/app.js"></script>
    <script src="scripts/site.js"></script>
    <script src="scripts/ajax.js"></script>
    <!-- endbuild -->

**

  • Startup.cs

**

namespace MusicSite
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets<Startup>();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseStaticFiles();

            // Add MVC to the request pipeline.
            app.UseMvc();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }

            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

【问题讨论】:

  • 你能添加你的startup.cs代码吗?或者请检查您是否添加了 StaticFiles() 中间件。
  • 我添加了我的启动代码
  • 在我的 .min 版本的文件中丢失了。我添加了 bundleconfig.json 文件的路径,它按预期工作。

标签: asp.net-core asp.net-core-mvc


【解决方案1】:

在 ASP.NET 核心中,默认情况下,静态文件仅来自 wwwroot 文件夹。这意味着如果您尝试从Libs 目录访问文件,它将无法正常工作。

好消息是,您可以根据需要配置静态文件位置。因此,请在 startup.cs 中更新您的 Configure 方法。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
                                                           ILoggerFactory loggerFactory)
{
     // Your existing code goes here

     app.UseStaticFiles();

     // This will add "Libs" as another valid static content location
     app.UseStaticFiles(new StaticFileOptions()
     {
        FileProvider = new PhysicalFileProvider(
              Path.Combine(Directory.GetCurrentDirectory(), @"Libs")),
        RequestPath = new PathString("/libs")
     });
}

PhysicalFileProvider 类在 Microsoft.Extensions.FileProviders 命名空间中定义。因此,您应该在 Startup.cs 类中添加 using 语句。

using Microsoft.Extensions.FileProviders;

现在可以从yourSiteName/libs/somejsfile.js 访问这些文件。此外,在这些脚本的路径前加上 ~/。 tilda(~) 标志表明它是应用程序根目录。

<script src="~/libs/jquery/dist/jquery.js"></script>

正如我之前提到的,wwwroot 是一个特殊文件夹,用于将您的静态资源保存在一起。因此,您也可以考虑将您的libs 目录移动到wwwwroot 下,然后一切正常,无需上述自定义配置。

【讨论】:

  • 我们只想托管来自wwwroot 的文件,但奇怪的是,当我们在完整框架中托管 ASP.NET Core 时,似乎必须在启动时明确指向 UseStaticFile() wwwroot,即app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")) });
  • 我必须翻转斜线才能在我的 Ubuntu 机器上工作 - app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot").Replace("\\", "/")) });
  • 对于.net 5 仍然是现实我有同样的问题。它找不到 wwwroot 文件夹中包含的静态文件。即使我移动应用程序根文件夹中的文件仍然找不到它,我会发帖。因为我被卡住了。我也将发布我的启动文件。我正在 ubuntu 服务器 20.04 上解聚
  • 将此代码放在您的 Nginx 配置文件中,替换为您的文件夹位置 - server { server_name yoursite name; # 这个位置块解决了我的问题。位置 ~* /(css|js|lib) { 根 /var/www/yoursite/net5.0/publish/wwwroot; }
猜你喜欢
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2016-11-07
  • 2011-10-22
相关资源
最近更新 更多