.NET Core handling Client-Side Routes





If you are using any client-side framework like VueAngularReact and so, you are probably doing client-side routing which is letting the browser handles the routes E.g.  myapp.com/about, myapp.com/account/user etc...

By default, the server only recognizes the root (/) and if you try to refresh the page (f5) or enter directly the URL myapp.com/about  you will get 404 ERROR because you are sending an HTTP request to the server in the route /about,  but your server doesn't handle routes different from (/).

To solve this problem I found a really nice approach which is a simple fallback handler in the Startup.cs of our .NET Core app: 


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
        ....Your configuration
      app.UseMvc(routes =>
      {
        routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
      });
      //handle client side routes
      app.Run(async (context) =>
      {
        context.Response.ContentType = "text/html";
        await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
      });
    }
 }

The code above will return the right route to the Browers avoiding the 404 error if the path exists.


Do you have any question or a better approach? share with us in the comments.

Popular posts from this blog

GitHub Pages + Vue CLI 3

A Closer Look at Pair Programming

Let's talk about Web Accessibility