将React+.NET Core3.1应用发布到IIS时遇AggregateException等异常求助
Hey there, let's break down what's going on here and fix it step by step!
Core Issue Explanation
The error happens because you're using UseReactDevelopmentServer with a build script (build/production) in production mode—and that's not what this method is for.
UseReactDevelopmentServer is designed to launch React's live development server (like your start script) during development, so ASP.NET Core can proxy requests to it. But your build and production scripts only compile React into static files (output to the build folder) and then exit immediately—they never start a long-running server to listen for requests. That's why ASP.NET Core throws an error saying the script exited without listening.
Correct Production Environment Setup
For production, you don't need to run a React development server at all. Instead, have ASP.NET Core serve the pre-built static files directly. Update your Startup.cs like this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Keep your existing middleware (like UseStaticFiles, UseRouting, etc.) here app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; // Adjust this to your React project's root path if (env.IsDevelopment()) { // Only use React dev server in development for hot reloading spa.UseReactDevelopmentServer(npmScript: "start"); } else { // In production, serve the pre-built static files from the build folder spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "ClientApp", "build")) }; } }); }
Before deploying to production, make sure you run your production build script first:
npm run production
This generates the optimized static files in the build folder. You can also configure Visual Studio to auto-run this script during publishing (check your publish profile settings for "Run npm script" options).
Debugging Steps to Troubleshoot Further
If you still run into issues, try these checks:
- Validate local build first: Run
npm run productionlocally and confirm thebuildfolder is created withindex.htmland all static assets (CSS, JS, images). - Check server file structure: After publishing, verify the
ClientApp/buildfolder exists on your server and has the correct files. - Run scripts manually on the server: SSH into your server, navigate to the React project directory, and run
npm run productiondirectly. Look for any error output that might indicate missing dependencies or build failures. - Verify static file middleware order: Ensure
app.UseStaticFiles()is placed beforeapp.UseSpa()in yourConfiguremethod—this lets ASP.NET Core serve static files properly. - Check environment variables: If your
.env.prodfile is required, make sure it's deployed to the server's React project directory, or set the variables directly on the server environment.
内容的提问来源于stack exchange,提问作者arkhz

