How to always default route for every request

I am using ASP.NET 5 / MVC 6 and I am hosting a AngularJS SPA.

I am using UI Router, which works fine, but when I refresh the page on a route, for example /customer/5 I get a blank page. I expect this is because I haven't got a route / controller associated with that route.

Ideally in this case I would want MVC to serve up "index.html" (my default page) that contains all my AngularJS code and then let UI router show the correct page.

How do I do this? Here is a subset of my current Configure function in Startup.cs

app.UseMvc();
app.UseDefaultFiles();

app.UseStaticFiles();

Answers


Add a custom Middleware before MVC in pipeline to handle all non-ajax and non-static file requests.

 app.UseStaticFiles();

 app.Use(async (context, next) =>
 {
      if (!Path.HasExtension(context.Request.Path.Value) && context.Request.HttpContext.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
      {
           await context.Response.WriteAsync(System.IO.File.ReadAllText("index.html"));
      }

      await next();
 });

 app.UseMvc();

I have the same issue when using Asp.net core 1.1 web api & SPA (React-Redux created from CLI) separately. I'm hosting SPA as static files inside wwwroot folder

The code below works for me.

 app.UseDefaultFiles();
 app.UseStaticFiles();

 app.Use(async (context, next) =>
 {
    if (!context.Request.Path.Value.Contains("/api"))
    {
        context.Response.Redirect("/");
        //context.Response.Redirect($"/#{context.Request.Path.Value}");
        return;
    }
    await next();
 });
 app.UseMvc();

Need Your Help

start URL rewriting in current folder

php apache .htaccess lamp

I have a website in a subdirectory of my domain (example.com/folder)

PHP - Line breaks from textarea not working

php preg-replace newline str-replace

I have written a script today for formatting text inside of my HTML emails from my form. Where I enter the message body of my email I use a textarea. I have been trying all day to figure out how to...