.NET Core 5 WebApi How to include React app

Viewed 380

I have developed .NET5 web api and React app in two different projects. Now it's time to deploy API and React app to IIS, but on trying to achieve that I realized that they have to be added as same app in IIS. I wish that routing setup would be:

  • / => React App
  • /api/v1/controller/method => API endpoints

Both of my apps individually has this setup, I just cannot merge them :/

I cannot find examples where dotnet template isn't used. So far I have tried to accomplish that through this code (I have skipped non related configurations code):

services.AddSpaStaticFiles(configuration =>
                    {
                        configuration.RootPath = "ClientApp";
                    });

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

I have managed to solve it by adding these lines:

in ConfigureServices

if (HostingEnvironment.IsProduction())
{
   services.AddSpaStaticFiles(configuration =>
 configuration.RootPath ="ClientApp");
}

in Configure
                app.UseHttpsRedirection();
                app.UseRouting();
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
                if (env.IsProduction())
                {
                    app.UseSpaStaticFiles();
                    app.UseSpa(spa =>
                    {
                        spa.Options.DefaultPage = "/index.html";
                    });

I have achieved in .NET 6 this by:

1 - Copying the production build of my React app to the Web API wwwroot folder, using a postbuild step in package.json

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "postbuild": "move build ../YourWebAPIProject/wwwroot",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

2 - Updated the program.cs in the Web API project to contain the following

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

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(config => 
{
    config.MapControllers();
    config.MapFallbackToController("Index", "Fallback");
});

3 - Add a fallback controller to handle the react routes

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace YourNameSpace
{
    [AllowAnonymous]
    public class FallbackController : Controller
    {
        public IActionResult Index()
        {
            return PhysicalFile(
                Path.Combine(
                    Directory.GetCurrentDirectory(), "wwwroot", "index.html"), 
                    "text/HTML");
        }
    }
}

This approach allows both WebAPI and React routes to work, served from the WebAPI project.

Hope this is useful to someone

Related