You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC与Web API项目中AngularJS路由失效问题

问题排查与解决方案

1. 修正ASP.NET MVC路由配置

由于启用了Angular的html5Mode,ASP.NET MVC的默认路由会拦截Angular路由请求,导致局部视图返回404。修改RouteConfig.cs,让所有非API请求都指向Home/Index,交给Angular接管路由:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // 保留API路由(如有)
        routes.MapRoute(
            name: "Api",
            url: "api/{controller}/{action}/{id}",
            defaults: new { id = UrlParameter.Optional }
        );

        // 所有其他请求转发到Home/Index
        routes.MapRoute(
            name: "Default",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

2. 完善AngularJS的html5Mode配置

启用html5Mode必须配合<base>标签,否则路由会出现路径错误。在Index.cshtml的<head>中添加:

<base href="@Url.Content("~/")" />

同时确保Module.js的路由配置正确:

angular.module('app', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
    $routeProvider
        .when('/login', {
            templateUrl: '/Views/User/Login.cshtml',
            controller: 'LoginController'
        })
        .when('/profile', {
            templateUrl: '/Views/User/Profile.cshtml',
            controller: 'ProfileController'
        })
        .when('/facility', {
            templateUrl: '/Views/Facility/Index.cshtml',
            controller: 'FacilityController'
        })
        .otherwise({ redirectTo: '/login' });

    $locationProvider.html5Mode({
        enabled: true,
        requireBase: true // 必须与<base>标签配合,不要设为false
    });
});

3. 检查局部视图的配置

  • 确保Login.cshtml、Profile.cshtml等局部视图的物理路径正确,比如~/Views/User/Login.cshtml确实存在
  • 局部视图需禁用MVC布局,在视图顶部添加Layout = null;,避免嵌套布局干扰Angular解析
  • 若视图位于Area中,templateUrl需包含Area路径,比如/Areas/Admin/Views/User/Login.cshtml

4. 修正页面跳转链接写法

使用Angular的ng-href替代普通href,避免触发整页刷新:

<!-- 错误写法 -->
<a href="/login">登录</a>

<!-- 正确写法 -->
<a ng-href="/login">登录</a>

5. 利用浏览器控制台定位错误

打开F12控制台查看:

  • 若出现404错误,检查templateUrl的路径是否与MVC视图的访问路径一致
  • 若出现Angular报错,确认控制器已正确注册到模块、依赖注入无误

内容的提问来源于stack exchange,提问作者Maryam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:52:19