如何同时配置 ASP.NET Core 3.1 应用程序到 运行 ReactJS 和 MVC 网站

How to configure ASP.NET Core 3.1 application to run ReactJS and MVC website side by side

我有一个 ASP.NET 使用 CRA 创建的核心 React 网站。 React 应用程序适用于只读 public 对开页面。

例如,我还希望将一些管理页面创建为 EF 内核脚手架 Razor 页面;

如何配置路由以适应这两种情况?

启动配置如下;

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllersWithViews();

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

            services.AddDbContext<MyDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
        }

        // 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: "admin",
                    pattern: "admin/{controller}/{action=Index}/{id?}");
            });

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

                if (env.IsDevelopment())
                {
                    //spa.UseReactDevelopmentServer(npmScript: "start");
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:3000");
                }
            });
        }

startup.cs 中,端点映射是为 MVC 配置的。这可以工作,但更改它会更容易;

改变

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
    name: "admin",
    pattern: "admin/{controller}/{action=Index}/{id?}");
});

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
});

信息来自 https://andrewlock.net/comparing-startup-between-the-asp-net-core-3-templates/ and https://www.learnrazorpages.com/razor-pages/routing