如何赶上所有错误(url)的请求到我的ASP.NET应用程序?

我有一个ASP.NET网站,并捕捉错误的URL请求,并将它们redirect到主页我把:

<customErrors defaultRedirect="/" mode="On"> <error statusCode="404" redirect="~/"/> </customErrors> 

在我的web.config

这只适用于像http://mywebsite/wrong.aspx这样的页面,但不适用于文件夹(例如: http://mywebsite/wrong-folder/

我明白,我必须赶上所有的要求,以解决这个问题,但我没有访问IIS来做ISAPI设置…

可以在web.config中完成吗? 你有没有例子?

<customErrors>...</customErrors>标记只控制发生错误时ASP.NET将执行的操作。 如果您访问一个不存在的目录,错误将由IIS处理,而不是由ASP.NET处理。

因此,您必须更改IIS的404处理。 这只能通过applicationHost.config文件来完成,但通常只能通过pipe理权限访问。 以下是该文件的摘录,它将404处理更改为特定网站的自定义页面:

 <location path="[Your Site Name]"> <system.webServer> <httpErrors errorMode="DetailedLocalOnly"> <remove statusCode="404" subStatusCode="-1" /> <error statusCode="404" prefixLanguageFilePath="" path="/your-404-handler.aspx" responseMode="ExecuteURL" /> </httpErrors> </system.webServer> </location> 

您也可以通过IIS Mananger通过以下Sites -> [Your Site Name] -> Error Pages -> 404更改: Sites -> [Your Site Name] -> Error Pages -> 404

这可以通过使用Microsoft URL重写来完成。 如果模块已安装,请将以下规则添加到web.config中。 任何不匹配“MyPage.aspx”的请求(不区分大小写)都会通过发出带有MyPage.aspx的HTTP 301作为新的位置来响应。 您需要在“条件”下将所有可接受的url列入白名单,不过这是使用自定义错误的替代方法。

 <configuration> <system.webServer> <rewrite> <rules> <rule name="RedirectToMyPage" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{REQUEST_URI}" pattern="^MyPage.aspx$" negate="true" /> </conditions> <action type="Redirect" url="MyPage.aspx" /> </rule> </rules> </rewrite> </system.webServer> </configuration> 

另一个select是利用URL重写和customErrors,通过configurationcustomErrors将404错误redirect到“/404Error.aspx”(不需要存在)之类的页面,然后有一个URL重写规则,将所有请求redirect到“ /404Error.aspx“到您的主页。 这个URL重写规则看起来像这样:

 <configuration> <system.webServer> <rewrite> <rules> <rule name="RedirectToMyPage" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{REQUEST_URI}" pattern="^404Error.aspx$" /> </conditions> <action type="Redirect" url="MyPage.aspx" /> </rule> </rules> </rewrite> </system.webServer> </configuration>