带有 Angular 的 ASP.NET MVC :- 页面刷新或重新加载会出现 404 错误加载、错误、页面、ASP

2023-09-06 08:45:30 作者:desire(欲望)

角度版本:5

我正在使用 ASP.NET MVC 开发一个新项目,并将 angular 5 与它集成.该项目工作正常,除了页面刷新产生 404 page not found 错误.每当我从浏览器点击刷新或重新加载页面时,它都会出现 404 错误.

I am working on a new project with ASP.NET MVC and have integrated angular 5 with it. The project is working fine except the page refresh yields the 404 page not found error. Whenever i hit refresh from the browser or reload the page, it gives the 404 error.

我已经阅读了很多关于这个 Angular 页面刷新问题的教程和讨论,但到目前为止还没有运气.

I have gone through many tutorials and discussions on this Angular page refresh problem, but no luck so far.

我正在使用 MVC 共享视图 _Layout.cshtml 来指定角度库引用和基础引用,如下所示:-

I am using the MVC shared view _Layout.cshtml to specify the angular lib references and the base reference as follows:-

  <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>

    <base href="/">

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/bootstrap")

    <script src="~/node_modules/core-js/client/shim.min.js"></script>
    <script src="~/node_modules/zone.js/dist/zone.js"></script>
    <script src="~/node_modules/systemjs/dist/system.src.js"></script>
    <script src="~/Web/systemjs.config.js"></script>
    <script>
        System.import('Web/main.js').catch(function (err) { console.error(err); });
    </script>
</head>
<body>
    @RenderBody()

    @RenderSection("scripts", required: false)
</body>
</html>

请建议我应该在哪里进行更改.

Please suggest where should i make the changes.

推荐答案

在位于 App_Start 的 RouteConfig 中将路由映射更改为此

In your RouteConfig located in App_Start change your route mapping to this

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

基本上这将捕获您的所有路线路径.

Basically this will capture all your route paths.

Angular 是一个 SPA 环境,因此您只需要一个 View 实例,即您的 HomeController

Angular is a SPA environment, so you only need a single instance of a View which is your HomeController