且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 ASP.NET MVC 和 AngularJS 路由?

更新时间:2023-02-16 16:12:53

感谢回答,agbenyezi.我看了你提供的文章,但它只能让我回到原来的状态.

Thanks for the answer, agbenyezi. I looked at the article you provided but it only got me back to where I was anyway.

但是,我能够弄清楚并使其正常工作.结果发现答案相对简单,但花了一些时间和大量的搜索.无论如何,由于我使用的是 MVC 区域,因此导航到 http://servername/Application1/view[x] 的 URL(其中 Application1 是 MVC 控制器(在该区域中)和 view1、view2、view3 等是 Angularjs 视图),整个应用程序的 MVC 部分变得混乱,并试图在 Application1 控制器(不存在)中找到名为 view[x] 的操作.

However, I was able to figure it out and get it working. The answer turned out to be relatively simple, but it took some time and a lot of searching around. Anyway, since I am using MVC areas, navigating to a URL of http://servername/Application1/view[x] (where Application1 is the MVC controller (in the area) and view1, view2, view3, etc. are Angularjs views), the MVC part of the overall application was getting confused and trying to find an action named view[x] in the Application1 controller (which doesn't exist).

因此,在该区域的 AreaRegistration 类中(它定义了该区域的特定路由),我只需要在任何默认 MVC 路由之前添加一种全能路由,以始终强制它执行应用程序控制器上的 Index 操作.类似的东西:

So, in the area's AreaRegistration class (where it's defining specific routes for the area), I just needed to add a kind of catch-all route before any default MVC routes to always force it to the Index action on the Application controller. Something like:

        // Route override to work with Angularjs and HTML5 routing
        context.MapRoute(
            name: "Application1Override",
            url: "Application1/{*.}",
            defaults: new { controller = "Application1", action = "Index" }
        );

现在,当我导航到 http://servername/Application1/view[x] 时,它路由到 Application1 MVC 控制器,Index 操作,然后 Angularjs 接管到不同视图的路由,同时在 URL 中包含 HTML5 路由结构.

Now, when I navigate to http://servername/Application1/view[x] it routes to the Application1 MVC controller, Index action, and then Angularjs takes over routes to the different views, all while having the HTML5 routing construct in the URL.

希望能帮助他人.

谢谢!