【问题标题】:Angular 2 - Routing with ASP.NET MVCAngular 2 - 使用 ASP.NET MVC 进行路由
【发布时间】:2017-05-10 03:48:45
【问题描述】:

我正在尝试将 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(角度路线)中,我刚刚定义了几条路线。我的默认路由重定向到另一条路由,例如

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 等。

【问题讨论】:

  • 为什么你不使用服务器端的一个路由和客户端的另一个路由?我的意思是让 razor 加载主视图并从 html 和 js 让角度路由器工作?
  • 在 angular2 中使用 asp.net MVC(作为用户界面)并不是一个好主意。
  • @HassanFalahi 是的,但当时要求使用身份服务器并使用内置模板进行用户管理

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


【解决方案1】:

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

【讨论】:

  • 真是救命稻草,一直在寻找这个解决方案。非常感谢
【解决方案2】:

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

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 控制器(Home、Account、Upload、Resource)。我的 spa-fallback 路由在默认路由下,所以如果我们输入除这些控制器名称以外的任何内容,Angular 将尝试使用默认 /Home/Index 服务器路径在其路由中找到它。

我希望它对某人有所帮助。

【讨论】:

  • 为什么这不是最好的方法?
猜你喜欢
  • 2017-10-04
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
  • 2018-04-24
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多