代码之家  ›  专栏  ›  技术社区  ›  Karan

带角度的ASP.NET MVC:-页面刷新或重新加载会产生404错误

  •  2
  • Karan  · 技术社区  · 8 年前

    角度:5

    我正在使用asp.net mvc开发一个新的项目,并将angular 5与之集成。项目工作正常,但页面刷新会产生404页未找到错误。每当我从浏览器中点击刷新或重新加载页面时,都会出现404错误。

    我已经完成了很多关于这个角度页面刷新问题的教程和讨论,但是到目前为止还没有运气。

    我正在使用MVC共享视图 _ layout.cshtml格式 指定角度lib引用和基引用如下:

      <!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>
    

    请建议我在哪里进行更改。

    2 回复  |  直到 8 年前
        1
  •  5
  •   John Velasquez    8 年前

    在你的 RouteConfig 位于 应用程序启动 将路由映射更改为此

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

    基本上这将捕获所有的路径。

    Angular是一个spa环境,因此您只需要 View 那是你的 HomeController

        2
  •  2
  •   J.Loscos    8 年前

    另一个解决方案是使用iis url重写将请求分派到应用程序的根目录,以让角度路由器处理路由。 通过放入web.config:

      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
    

    这个url重写规则重写为/每个不以/api开头,并且与物理文件或文件夹不匹配的url。

    推荐文章