React-router urls don't work when refreshing or writing manually

前端 未结 30 2723
时光取名叫无心
时光取名叫无心 2020-11-21 05:07

I\'m using React-router and it works fine while I\'m clicking on link buttons, but when I refresh my webpage it does not load what I want.

For instance, I am in

30条回答
  •  广开言路
    2020-11-21 05:30

    As I am using .Net Core MVC something like this helped me:

        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                var url = Request.Path + Request.QueryString;
                return App(url);
            }
    
            [Route("App")]
            public IActionResult App(string url)
            {
                return View("/wwwroot/app/build/index.html");
            }
       }
    

    Basically in MVC side, all the routes not matching will fall into to Home/Index as it specified in startup.cs. Inside Index it is possible to get the original request url and pass it wherever needed.

    startup.cs

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
    
                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
    

提交回复
热议问题