1

I have an MVC Razor app that I have just converted to a Single Page Application using AngularJS and Angular UI Router.

I have a problem in that when I go to a URL (via a refresh) such as /settings/options MVC attempts to look for the Options() method on the Settings controller. Once the page has finished loading the Angular routing takes over and shows the correct page.

Because my layout page HAS to have a RenderBody() call (else an exception is thrown) I end up with my page looking correct but having a 404 page at the bottom. The 404 is rendered into RenderBody because it cannot find the Options() method on the Settings controller

How can I fix this? I presume using some kind of MVC Routing but not sure where to start. Here is my current route

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

This question has a similar problem except they use WebAPI and I have my endpoints within a normal controller. If I use the solution here all my AJAX requests get redirected too

Community
  • 1
  • 1
Chris
  • 26,744
  • 48
  • 193
  • 345

1 Answers1

1

I feel like this question (How to use ASP.NET MVC and AngularJS routing?) might help you. They're using different "Areas" of the site, but it's the same concept for the routing.

You could also look into the URL Rewriter for IIS config and use that to make rules to always route your SPA requests to the angular app... How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

Community
  • 1
  • 1
molson504x
  • 1,180
  • 10
  • 18
  • That linked helped me when i started off too! – Ric Oct 20 '15 at 12:47
  • Unfortunately my web AJAX handlers dont sit nicely under `/api` or similar - thats a shame! – Chris Oct 20 '15 at 13:11
  • @Chris where do your ajax handlers sit? – molson504x Oct 20 '15 at 13:15
  • Unfortunately within my normal controllers (where the view handlers used to be). Ive found a solution atm involving interception errors in Global.asax and redirecting none Ajax requests to Home/Index. Long term I'd like to implement what you posted though - move my API calls to /API/ etc – Chris Oct 20 '15 at 13:29
  • @Chris you could have 2 HTTP rewrite handlers... Something like "If I see a URL with /api/" in there, strip the "/api" part out and toss the request through... Otherwise, send it through to the angular SPA route" – molson504x Oct 20 '15 at 13:42