本文介绍了而无需重写URL显示自定义ASP.NET错误页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前工作的错误页面为我在ASP.NET网站。我使用的Web配置文件将用户重定向到一个错误页面,如果服务器找不到请求的网页。下面是我在配置文件中使用的标签的customErrors:

Currently working on error pages for my website in ASP.NET. I'm using a web configuration file to redirect the user to an error page if the server was unable to find the requested page. Below is the customErrors tag I used in my configuration file:

<customErrors mode="On" defaultRedirect="~/ErrorPages/Error.aspx">
  <error statusCode="404" redirect="~/ErrorPages/Error.aspx"/>
</customErrors>

目前它的工作,但我的问题是,我不希望用户看到我的错误页的URL,如下显示:

It's currently working but my problem is that I don't want the user to see my error page in the URL as displayed below:

/MySite/ErrorPages/Error.aspx?aspxerrorpath=/MySite/ImaginaryPage.aspx

/MySite/ErrorPages/Error.aspx?aspxerrorpath=/MySite/ImaginaryPage.aspx

我期待着什么像什么谷歌有:

I'm expecting something like what google has:Google Error Page

有没有办法做到这一点没有JavaScript?

Is there a way to do this without Javascript?

推荐答案

这篇文章可能会帮助你,这里是从它的代码段:
http://blog.dmbcllc.com/aspnet-application_error-detecting-404s/

This article might help you out and here is a snippet from it:http://blog.dmbcllc.com/aspnet-application_error-detecting-404s/

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    if (ex is HttpException)
    {
        if (((HttpException)(ex)).GetHttpCode() == 404)
            Server.Transfer("~/Error404.aspx");
    }
}

真的这样做的关键部分是,如果你想保持相同的URL请求的,那么的Response.Redirect 是不是你想要的东西,因为它可以追溯到客户端发出从而改变URL的第二请求。你想留在服务器上,以便在适当的呼叫将 Server.Transfer的。这种特殊的事件处理程序进入你的Global.asax.cs文件和方法会兴起对于那些应用程序的上下文中相关的任何404。

Really the key part of this is if you want to maintain the same URL as what was requested, then Response.Redirect is NOT what you want as it goes back to the client to issue a second request thus changing the URL. You want to remain on the server so the appropriate call would be Server.Transfer. This particular event handler goes into your Global.asax.cs file and the method will get raised up for any 404s that are associated within the context of your application.

不幸的是,它会跳过你的的customErrors 配置部分并依靠更加编程方法不过code是从维护的角度来看相当简单的。

Unfortunately, it will skip past your customErrors configuration section and rely on a more programmatic approach however the code is fairly simple from a maintenance standpoint.

这篇关于而无需重写URL显示自定义ASP.NET错误页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!