React Router with ASP.NET Core Web API 6.0, route all non /api calls to react app

Viewed 304

I have a React App using React Router Dom, I have been trying to figure out how to get client-side routing working, if I load the web app normally everything works fine, and I can access different components at different URLs using react-router-dom.

But if I refresh or try and access the url to a routed component directly, the server returns 404 not found as its making a request not to my SPA but the server.

I was wondering how in a .net 6.0 Web api, how to route anything not beginning with /api to my SPA.

Thanks!

1 Answers

After lots of trial and error, adding

app.MapControllerRoute(
  name: "api",
  pattern: "/api/{controller=Home}/{id?}");

app.MapFallbackToFile("/index.html");

to Program.cs, I was able to have the fallback url map back to index.html

Related