Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 658
Jacob Stephenson Avatar asked Dec 05 '25 10:12

Jacob Stephenson


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

like image 52
Jacob Stephenson Avatar answered Dec 07 '25 22:12

Jacob Stephenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!