Chris
Chris

Reputation: 27384

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();

Upvotes: 3

Views: 1495

Answers (2)

Hung Quach
Hung Quach

Reputation: 2177

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();

Upvotes: 1

tmg
tmg

Reputation: 20383

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();

Upvotes: 5

Related Questions