Angular 2 - 使用 ASP.NET MVC 进行路由

Angular 2 - Routing with ASP.NET MVC

我正在尝试将 ASP.NET MVC(非核心)与 AngularJS 2 一起使用,但在路由方面存在一些问题。

首先在 RouteConfig.cs,我定义了以下路线

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

// when the user types in a link handled by client side routing to the address bar 
// or refreshes the page, that triggers the server routing. The server should pass 
// that onto the client, so Angular can handle the route
routes.MapRoute(
    name: "spa-fallback",
    url: "{*url}",
    defaults: new { controller = "Home", action = "Index" }
);

在我的 app.route.ts(angular 路线)中,我刚刚定义了几个路线。我的默认路由重定向到其他路由,如

export const router: Routes = [{
        path: '',
        redirectTo: 'auctions/e231',
        pathMatch: 'full'
    },
    {
        path: 'auctions/:id',
        component: AuctionComponent,
        children: []
    }
];

当我 运行 应用程序时,我的服务器路由 /Home/Index 正常运行,它加载了 angular 应用程序,我的 app.route.ts 中的默认路由将我重定向到 auctions/e231 而我浏览器的最终 URL 变成了

http://localhost:53796/auctions/e231

一切都按预期工作,但是当我用这个 URL 刷新页面时,我收到一个服务器错误,因为找不到资源,这也是预期的,因为它寻找一个名为 Auctions 的控制器,它不存在于MVC。我想知道为什么我在 RouteConfig.cs 的 spa-fallback 路线没有被接收到?在 asp.net mvc 中还有更好的方法来处理这种情况,因为我希望能够使用我的 MVC 控制器的一些操作,如 /Account/Login 和其他操作。

问题是当您刷新页面时,将使用第一个路由,因为它会尝试获取名为 Auctions 的控制器。如果你删除第一个路由配置(默认)并且只使用第二个(spa-fallback),它会工作正常,这就是我在我的项目中使用的方式,只在 spa-fallback 之前放置你想要重定向到其他的其他 mvc 路由MVC 控制器。

虽然在我看来这不是最好的方法,但仍然有效。我使用路线中的约束使其工作。我将默认路由更新为:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    constraints: new { controller = "Home|Account|Upload|Resource" } // this is basically a regular expression
);

我只有 4 个 MVC 控制器(主页、帐户、上传、资源)。我的 spa-fallback 路由在默认路由下,所以如果我们键入这些控制器名称以外的任何内容,angular 将尝试在其路由中使用默认 /Home/Index 服务器路径找到它。

希望对大家有所帮助。