4

I'm building a SPA application using React-Router to handle the front-end routing.

I'm trying to configure the ASP.NET 5 Startup.cs file to use MVC but when a route does not match any of my API routes to send the index.html file so that it will be able to handle react-routers browser history implementation as stated here.

So far i've only been able to get it to send the index.html file when on the default route, i.e. nothing after the localhost:3000.

My Startup Configure method so far. Thank you

        app.UseIdentity();
        app.UseIISPlatformHandler();
        app.UseDefaultFiles(new DefaultFilesOptions {
            DefaultFileNames = new List<string> { "index.html"}
        });
        app.UseStaticFiles();
        app.UseMvc();
tanguy_k
  • 11,307
  • 6
  • 54
  • 58
Akram Ali
  • 41
  • 1
  • 3
  • 2
    Essentially this is handing 404 errors, if a route/page doesn't exist then you want to show something else. Check out this question and answer here: http://stackoverflow.com/questions/29421164/mvc-6-404-not-found – ZeroBased_IX Dec 28 '15 at 13:32
  • Thank you, i'll give that a go – Akram Ali Dec 28 '15 at 15:24

1 Answers1

6

Pretty simple, with app.UseStatusCodePagesWithReExecute("/");

public void Configure(IApplicationBuilder app)
{
    app.UseIISPlatformHandler();

    app.UseStatusCodePagesWithReExecute("/");

    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}"
        );
    });
}

This will return the index.html page in your wwwroot, even if you get a 404. It will however only change the page, but not the URL.

Alternatively, you might not want to do a page redirect since you are doing a SPA, but if you really need to update the URL you can just do a simple redirect from a controller, like so:

public class RedirectController : Controller
{
    public IActionResult Index()
    {
        return Redirect(Url.Content("~/"));
    }
}

and then in your startup update this:

app.UseStatusCodePagesWithReExecute("/redirect");
Nick De Beer
  • 5,232
  • 6
  • 35
  • 50
  • Very nice! Note that the order is important (`app.UseStatusCodePagesWithReExecute` should be before `app.UseDefaultFiles` from what I have tested). Also `app.UseMvc()` is enough if you don't have any "view", just index.html for your SPA. Instead of defining `RedirectController` (if you need a 302 redirection), you can use `UseStatusCodePagesWithRedirects` (did not test myself). See https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling – tanguy_k Dec 08 '16 at 01:41
  • thanks a lot @Nick De Beer, as your answer highlighted that `UseStatusCodePagesWithReExecute()` needs to be passed an URL, not a "path to the view" – superjos Jan 02 '17 at 22:10