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

标签 asp.net-mvc angular asp.net-mvc-4 angular-routing

我正在尝试将 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 刷新页面时,我收到未找到资源的服务器错误,这也是预期的,因为它会查找 MVC 中不存在的名为 Auctions 的 Controller 。我想知道为什么我在 RouteConfig.cs 中的 spa-fallback 路由没有被接收到?在 asp.net mvc 中还有更好的方法来处理这种情况,因为我希望能够使用我的 MVC Controller 的一些操作,如/Account/Login 和其他操作。

最佳答案

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

关于asp.net-mvc - Angular 2 - 使用 ASP.NET MVC 进行路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41318376/

相关文章:

mysql - 如何在两个表中建立外键关系

asp.net-mvc - FileStreamResult 和 FilePathResult 之间的区别?

angular - 如何将 ngrx-effect 中的 Action 的 action.payload 传播到 catchError 或 map 运算符?

javascript - 一个组件中的 ngForm 给出表单值,其他组件中的相同代码给出未定义

css - chrome 和 IE 中的 iframe 滚动条问题

css - MVC4 中的条件属性不起作用?

asp.net-mvc - 如何使用可空类型的强类型 HTML 助手?

c# - 如何从 asp.net mvc 3 应用程序中的 App_Data 文件夹中删除文件?

css - 服务器端渲染时图像在加载时拉伸(stretch)到 100%

jquery - 不引人注目的验证在 MVC4 中不断突破