在AngularJS中如何为任何无效的URL返回404状态代码?

时间:2018-03-23 06:23:09

标签: angularjs asp.net-mvc

站点是在AngualrJS中开发的,并部署在IIS Web服务器上。我们只在页面上,即Index.html,因为它是单页面应用程序。对于SEO目的,我们使用prerender.io。

在web.config文件中添加以下代码,将每个URL重写为根路径

<rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}"  matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>

还使用以下代码将所有无效的URL处理到main.module.js中,该代码将重定向到错误页面。

$urlRouterProvider.otherwise(function ($injector, $location) {
            var $state = $injector.get('$state');
            var $rootScope = $injector.get('$rootScope');
            var now = new Date(); now.setTime(now.getTime() + 1 * 1800 * 1000);
            setContentCookie('dlerrorURL', $location.$$absUrl, now.toUTCString(), 'xyz.com')
            $rootScope.error = true;
            $state.go('app.newerror')
        });

在上面的代码的帮助下,状态代码404出现在prerender.io上,但是如果我们在开发者控制台中查看netowrk选项卡,它会显示所有无效URL的200状态代码。从技术上讲,它是正确的,因为我们在web.config文件中添加了规则来重写所有URL到根路径。

经过大量的发现后,我们找到了解决方案,我们必须通过实现Asp.Net MVC代码并将所有路由添加到route.config文件中来保留服务器端的所有URL。因此,如果URL不匹配,它将返回404状态代码。

但由于我们有300多页,我们正避免实施上述解决方案。是否有任何替代方法来获取或设置无效URL的404状态代码。

1 个答案:

答案 0 :(得分:1)

根据我迄今为止的经验,我遇到了同样的问题,我们做了一些这样的改变,它对我们来说就像魅力一样!

请按照以下步骤操作:

第1步: 转到MVC应用程序中的 RouteConfig.cs 你会看到一些像这样的路线图..

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

现在评论该默认路线并添加一个像这样的其他地图路线

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

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

在上面的地图路线名称为HOME,您会看到类似 dv 的内容,您可以将其替换为任何关键字,例如 api 或项目的任何首字母,例如 abc xyz 我们这样做只是为了分隔带有角度路由的服务器路由。

删除您在网页配置中为URL重写编写的代码。 对于PRERENDER:

在web.config

中添加类似的内容
<configSections> 
<section name="prerender" type="Prerender.io.PrerenderConfigSection, Prerender.io, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<prerender  token="YOUR_TOKEN_HERE"></prerender>

并将 prerender.io DLL 添加到您的MVC项目中。

现在,在 system.web 中为prerender添加类似的内容。

<system.web> 
<httpModules>
<add name="Prerender" type="Prerender.io.PrerenderModule, Prerender.io, Version=1.0.0.2, Culture=neutral, PublicKeyToken=null"/>
</httpModules> 
</system.web>

现在,在MVC应用程序的 App_Start 文件夹中,添加此类名称 PreApplicationStartCode.cs

public static class PreApplicationStartCode
    {
         private static bool _isStarting;
        public static void PreStart()
        {


                if (!_isStarting)
                {
                    _isStarting = true;

                    DynamicModuleUtility.RegisterModule(typeof(Prerender.io.PrerenderModule));
                }

        }
    }

在你的MVC应用的属性下的 AssemblyInfo.cs 中,在文件的最后一行添加类似这样的预渲染。

[assembly: PreApplicationStartMethod(typeof(yourappnamespace.PreApplicationStartCode), "PreStart")]