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

Ali*_*aig 7 asp.net-mvc asp.net-mvc-4 angular-routing angular

我试图使用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" }
);
Run Code Online (Sandbox Code Playgroud)

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

export const router: Routes = [{
        path: '',
        redirectTo: 'auctions/e231',
        pathMatch: 'full'
    },
    {
        path: 'auctions/:id',
        component: AuctionComponent,
        children: []
    }
];
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,我的服务器路由/主页/索引服务正常,加载我的app.route.ts中的角度应用程序和默认路由重定向到auction/e231,我的浏览器的最终URL变为

http://localhost:53796/auctions/e231
Run Code Online (Sandbox Code Playgroud)

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

小智 7

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


Ali*_*aig 5

虽然我认为这不是最佳方法,但仍然有效。我使用路线中的约束使它正常工作。我将默认路线更新为:

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
);
Run Code Online (Sandbox Code Playgroud)

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

希望对您有所帮助。