如何在 ASP.NET-MVC 中显示自定义 404 页面?

发布于 2024-08-03 20:16:19 字数 482 浏览 1 评论 0原文

当我的网站上的任何 URL 为 404 时,我想显示使用 ASP.NET-MVC 呈现的自定义 404 页面。然而我不想使用通配符路由方法,因为这会禁用标准网络表单。我的代码目前如下所示:

if (serverException is HttpException && ((HttpException)serverException).GetHttpCode() == 404)
{
 //Server.Transfer("~/Test.aspx"); //1
 //Server.Transfer("~/error/gf54tvmdfguj85fghf/404"); //2
}

此代码位于 App_Error

//1 内,可以正常工作。 Test.aspx 是一个标准的 webform

//2 不起作用,因为它是一个 asp.net-mvc 路由

如何使 MVC 路由工作?

When any URL is 404 on my site, i want to show a custom 404 page that is rendered with ASP.NET-MVC. Hoewever i do not want to use the wildcard route approach because that would disable standard webforms. My code currently looks like this:

if (serverException is HttpException && ((HttpException)serverException).GetHttpCode() == 404)
{
 //Server.Transfer("~/Test.aspx"); //1
 //Server.Transfer("~/error/gf54tvmdfguj85fghf/404"); //2
}

this code is inside App_Error

//1 does work. Test.aspx is a standard webform

//2 does not work as it is an asp.net-mvc route

How to make the MVC-route work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

归属感 2024-08-10 20:16:19

您可以使用应用程序错误事件...如下所示:

 protected void Application_Error(object sender, EventArgs e)
{
  //Check if it's a 404 error:
  Exception exception = Server.GetLastError();
  HttpException httpException = exception as HttpException;

  if(httpException.GetHttpCode() == 404) {
      //Redirect to the error route
     Response.Redirect(String.Format("~/Error/404/?message={0}", exception.Message));
  }
}

You could use the application error event... like this:

 protected void Application_Error(object sender, EventArgs e)
{
  //Check if it's a 404 error:
  Exception exception = Server.GetLastError();
  HttpException httpException = exception as HttpException;

  if(httpException.GetHttpCode() == 404) {
      //Redirect to the error route
     Response.Redirect(String.Format("~/Error/404/?message={0}", exception.Message));
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文