You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8中非根路径运行React SPA超时问题求助

解决方案:ASP.NET Core 多路径React(Vite)应用访问超时问题

问题根源

你遇到的超时错误是因为UseReactDevelopmentServer是ASP.NET Core专门为create-react-app设计的中间件,它会等待cra开发服务器启动并监听端口,但你实际使用的是Vite,两者逻辑不兼容,导致ASP.NET Core一直等待不存在的cra服务器,最终触发超时。

修复步骤

1. 修改SPA扩展方法,适配Vite

替换原有的EnableReactApp方法,改用通用的代理逻辑对接Vite:

public static class SpaApplicationBuilderExtensions
{
    public static void EnableReactViteApp(this WebApplication app, string spaPath, string codePath, int serverPort, bool isDev = false)
    {
        ArgumentNullException.ThrowIfNull(app);
        ArgumentException.ThrowIfNullOrEmpty(spaPath);
        ArgumentException.ThrowIfNullOrEmpty(codePath); 

        app.Map(new PathString(spaPath), client =>
        {
            client.UsePathBase(new PathString(spaPath));
            
            if (isDev)
            {
                // 开发环境直接代理到已启动的Vite服务器
                client.UseProxyToSpaDevelopmentServer($"https://localhost:{serverPort}");
            }
            else
            {
                // 生产环境部署编译后的静态文件
                client.UseSpaStaticFiles();
                client.UseSpa(spa =>
                {
                    var parentDir = Directory.GetParent(Directory.GetCurrentDirectory())?.FullName ?? string.Empty;
                    spa.Options.SourcePath = Path.Combine(parentDir, codePath);
                    spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(Path.Combine(parentDir, codePath, "dist")),
                        RedirectToAppendTrailingSlash = true,
                    };
                });
            }
        });
    }
}

2. 更新Program.cs中的调用

替换原有的EnableReactApp调用为新的方法:

// 替换之前的app.EnableReactApp(...)
app.EnableReactViteApp("/spa1", "cs.web.client", 707, app.Environment.IsDevelopment());

3. 调整Vite配置,适配路径前缀

修改vite.config.ts,添加路径前缀并调整代理规则:

const baseFolder = env.APPDATA !== undefined && env.APPDATA !== ''
    ? `${env.APPDATA}/ASP.NET/https`
    : `${env.HOME}/.aspnet/https`;

const certificateName = "cs.web.client";
const certFilePath = path.join(baseFolder, `${certificateName}.pem`);
const keyFilePath = path.join(baseFolder, `${certificateName}.key`);

if (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {
    if (0 !== child_process.spawnSync('dotnet', [
        'dev-certs',
        'https',
        '--export-path',
        certFilePath,
        '--format',
        'Pem',
        '--no-password',
    ], { stdio: 'inherit', }).status) {
        throw new Error("Could not create certificate.");
    }
}

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
    env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:7788';

export default defineConfig({
    plugins: [plugin()],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    // 配置React应用的基础路径,对应ASP.NET中的/spa1
    base: '/spa1/',
    server: {
        proxy: {
            // 代理所有非Vite静态资源的请求到ASP.NET服务器
            '^/(?!spa1)': {
                target,
                secure: false,
                changeOrigin: true
            },
            // 保留原有API代理(如果需要)
            '^/weatherforecast': {
                target,
                secure: false
            },
        },
        port: 707,
        https: {
            key: fs.readFileSync(keyFilePath),
            cert: fs.readFileSync(certFilePath),
        },
        // 允许ASP.NET代理访问Vite服务器
        cors: true
    }
})

额外说明

  • 确保Vite服务器先于ASP.NET Core启动,或者在启动ASP.NET时自动启动Vite(可以在csproj中添加预构建命令)。
  • 生产环境下需要先执行Vite的构建命令(npm run build)生成dist目录,ASP.NET会自动从该目录加载静态文件。

内容的提问来源于stack exchange,提问作者JakeB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:06:01