asp.net mvc6 / angular2路由

时间:2016-05-27 09:26:54

标签: asp.net-mvc-routing angular2-routing

我有asp.net mvc6项目。在客户端,我想使用angular2来创建单页面应用程序。这意味着我有两个地方可以定义路由。 至于它的SPA,路由必须在angular2方面,但如果用户刷新页面时如何处理? MVC返回404。

一种方法是在mvc6中设置启动路由:

 routes.MapRoute(
            name: "spa-fallback",
            template: "{*url}",
            defaults: new { controller = "OAuth", action = "Index" });
        });

然后控制器将Request.Path提供给angular2。

但是这个{* url}无法识别* .map和其他静态文件。 此外,我可能会喜欢使用静态页面,如Error.html等。

有没有更好的方法来处理(服务器/客户端)端的路由?

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,决定使用视图而不是静态文件。

我已经设置了一个带有2个动作的Home控制器的MVC:索引和登录。

index.cshtml中的app boostraps和login.cshtml是一个简单的登录页面。

我的startup.cs文件中的路由以这种方式配置:

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "login",
                template: "login",
                defaults: new { controller = "Home", action = "Login" });
            routes.MapRoute(
                 name: "spa-fallback",
                 template: "{*url}",
                 defaults: new { controller = "Home", action = "Index" });
        });

在我的AppComponent中(使用Angular RC1):

@Routes([
    { path: '/Dashboard', component: Dashboard}
])

http://localhost/Dashboard中刷新页面会让我看到仪表板视图,而http://localhost/Login会将我重定向到登录页面,而不是角度应用程序。)

希望这有帮助