Search code examples
angularjsasp.net-mvcdnx

AngularJS with MVC 6


This is an MVC 6/WebApi application. I'm attempting to use WebApi on the backend with AngularJS on the frontend.

I have two static files: index.html and login.html
(There will eventually be more static files.)

My Angular app is contained in the index.html while views (such as /login) are loaded from static files (i.e. login.html).

If I go to my root URL, index.html is loaded just fine. However, if I go to /login, I receive a 404 page not found.

Now, let it be said, I DO NOT want to bog down my application with a bunch of controllers and views as it's unnecessary to simply serve static files. That's overkill.

I have my routes setup to serve API calls (i.e. ~/api/whatever). How I get MVC 6 to ignore all other routes?

FYI, it also appears that MapPageRoute is deprecated in MVC 6?

EDIT:
One thing I've done to actually get it working is add my own middleware to intercept the request. The code below is added after all of my default middleware in the Configure method:

app.Use(next => async context =>
{
    if (context.Request.Path.Value.StartsWith("/api"))
        await next.Invoke(context);
    else
        await context.Response.WriteAsync(System.IO.File.ReadAllText("index.html"));
});

This seems a bit much and it's just a hack. All it does is allows any request that begins with "/api" to go through (which is then picked up by the MVC middleware), but any other call is served with the contents of the index.html. So, if my requested URL is "/login", the index.html file is served, then Angular looks at the route and loads the login.html file into view.

Any other suggestions?


Solution

  • Okay, so since something didn't exist in the MVC 6/ASP.NET 5 framework, I've created my own middleware that provides a lot more flexibility. It has been added to GitHub and is available through NuGet.

    The project page is: https://github.com/a11smiles/AngularMiddleware