首页 > 解决方案 > 不使用 SPA (React) 启动 ASP.net 服务

问题描述

请帮我启动网络服务。我从文件夹“\bin\Debug\net 5.0”运行 .exe 文件。提示时https://localhost:5001/给出错误。我在 spa.Options.sourcepath 中指定了它,但它没有帮助。

我收到的错误如下:

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HMD866NK2DDC", Request id "0HMD866NK2DDC:00000011": An unhandled exception was thrown by the application.
      System.InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
Your application is running in Production mode, so make sure it has been published, or that you have built your SPA manually. Alternatively you may wish to switch to the Development environment.

这是文件夹结构ClientApp Paths

我的配置代码:

 public void ConfigureServices(IServiceCollection services)
        {
            // получаем строку подключения из файла конфигурации
            string connection = Configuration.GetConnectionString("DefaultConnection");
            // добавляем контекст ApplicationContext в качестве сервиса в приложение
            services.AddDbContext<ApplicationContext>(options =>
                options.UseSqlServer(connection));

            //чтобы кирилица нормально отображалась
            services.AddWebEncoders(o =>
            {
                o.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Cyrillic, UnicodeRanges.CyrillicExtendedA, UnicodeRanges.CyrillicExtendedB);
            });

            services.AddControllersWithViews();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }

标签: asp.netreactjssingle-page-application

解决方案


React 资产不是由 dotnet build 或 dotnet run 构建的,即使使用 -c Release 也不是。

要构建 React 资产,您还需要 dotnet publish。

由于较早使用 dotnet publish,此要求可能会被资产的存在所掩盖。在这种情况下,它们可能是陈旧的。因此,对于 dev 以外的任何环境,都必须使用 dotnet publish。

为什么不 dotnet build 和 dotnet run 构建 React 资产?在开发中,您不需要它们,因为您正在使用开发服务器进行热交换。在生产中,您几乎肯定会使用由 dotnet publish 准备的资产。

AspNetCore React 只能在 dev 模式下查找 spa 文件


推荐阅读