【问题标题】:Merge separate ReactJS client frontend application with ASP.NET Core backend API?将单独的 ReactJS 客户端前端应用程序与 ASP.NET Core 后端 API 合并?
【发布时间】:2019-10-29 16:00:56
【问题描述】:

我正在开发一个带有 ASP.NET Core 后端的全栈 Web 应用程序,该后端服务于 REST 和 GraphQL API。 .NET Core 应用在 Visual Studio 中的结构如下:

Backend.API: the API portion of the project that contains all the controllers and GraphQL query/mutation definitions that the front-end application consumes.  
Backend.Core: the portion of the back-end that defines all the user & application models used by the Backend.Data portion.  
Backend.Data: interacts with the database and defines all the repositories that the Backend.API portion uses when returning data for GraphQL queries, etc.

后端 .NET Core API 由完全独立于 C# 项目的前端 ReactJS 应用程序使用(创建为单独的 ReactJS 应用程序)。

我不想使用 ReactJS ASP.NET Core 模板,因为我想保持前端和后端之间的关注点分离,这样的模板会模糊不清。到目前为止,我已经能够通过提供后端启动的 localhost URL 来允许前端 ReactJS 应用程序使用后端 ASP.NET Core API(即 ReactJS 应用程序在 localhost:3000 上启动并从 API 获取localhost:5437 上的端点,其中后端由 Visual Studio 启动)。但是,当我想部署网站时,这两个部分之间的分离是不可行的——我需要将前端和后端项目结合起来,以便它们在同一个 URL 下运行。

因此,这提出了一个问题:将我的单独前端 ReactJS 应用程序与我的后端 ASP.NET Core API 合并以便它们在单个 URL 下运行的最佳方法是什么?

【问题讨论】:

  • 你使用 React-Router 吗?
  • 是的,ReactJS 前端使用 React Router,以及 Redux 和 Apollo GraphQL。
  • 路由层次结构中最长的链是什么? (/resources/1/edit 等)

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


【解决方案1】:

如果我在你的位置上,我会这样做:

  1. 我会将 Backend.API 重命名为 Backend.Web
  2. 将我的整个 React 应用移到 wwwroot 文件夹中
  3. 创建一个中间件,它将为我的 React 应用程序index.html 页面提供服务

          app.Use(async (context, next) =>
          {
            await next();
            var path = context.Request.Path.Value;
    
            if (!path.StartsWith("/api") && !Path.HasExtension(path))
            {
              context.Request.Path = "/index.html";
              await next();
            }
          });
    
    1. 确保管道中包含默认文件和静态文件的中间件:

    app.UseDefaultFiles(); app.UseStaticFiles();

  4. Index.html 将链接在 ReactJS 应用程序构建后创建的 JavaScript 和 CSS。

【讨论】:

  • 这个解决方案似乎有效。但是,您似乎也可以在 Startup.cs 中使用 app.UseSpa() 以及基于 React ASP.NET Core 模板的正确配置。
猜你喜欢
  • 2019-08-16
  • 2018-11-13
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 2021-06-07
相关资源
最近更新 更多