skip to Main Content

I’m currently using HashRouter and it works really well. However I would like to be able to use the # on sub routes as well for linking to paragraphs. For example /details#Summary. As a benefit I will also get cleaner URLs and if needed I can get some SEO.

Works and gives correct results on refresh/direct link.

<HashRouter>
    <App />
</HashRouter>

Works but gives 404 on refresh/direct link.

<BrowserRouter>
    <App />
</BrowserRouter>

enter image description here

I understand that the problem here is my routing in .Net and I need to change it. What do I need to do? I have a default route but it does not get hit.

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

2

Answers


  1. Chosen as BEST ANSWER

    First remove the standard routes.MapRoute that is shown above and then add this:

    routes.MapRoute("Client", "{*anything}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    

    Now any route will render your default action.

    Optional:

    If you have a controller with attribute routing, example:

    [RoutePrefix("Home")]
    public HomeController : Controller {
        //GET Home/Index
        [HttpGet]
        [Route("Index")]
        public ActionResult Index() {
            return View(); 
        }
    }
    

    You also need to add:

    routes.MapMvcAttributeRoutes();
    

  2. The thing is that when you change that, asp.net keeps trying to match a route from for details.

    What you need to do is create a route that matches all paths, so that it returns the default one, eg: home/index

    This is the route I use:

    routes.MapRoute(
      "Default",
      "{*url}",
      new { controller = "Home", action = "Index" });
    

    That will give control to the browser to math the paths after ‘/’

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search