【发布时间】:2011-03-26 18:19:44
【问题描述】:
我目前有一个继承自 System.Web.Mvc.Controller 的 BaseController 类。在该课程中,我有 HandleError 属性,可将用户重定向到“500 - 糟糕,我们搞砸了”页面。这目前正在按预期工作。
这行得通
<HandleError()> _
Public Class BaseController : Inherits System.Web.Mvc.Controller
''# do stuff
End Class
我的 404 页面也以 Per-ActionResult 为基础工作,它再次按预期工作。
这行得通
Function Details(ByVal id As Integer) As ActionResult
Dim user As Domain.User = UserService.GetUserByID(id)
If Not user Is Nothing Then
Dim userviewmodel As Domain.UserViewModel = New Domain.UserViewModel(user)
Return View(userviewmodel)
Else
''# Because of RESTful URL's, some people will want to "hunt around"
''# for other users by entering numbers into the address. We need to
''# gracefully redirect them to a not found page if the user doesn't
''# exist.
Response.StatusCode = CInt(HttpStatusCode.NotFound)
Return View("NotFound")
End If
End Function
同样,这很好用。如果用户输入http://example.com/user/999 之类的内容(其中用户ID 999 不存在),他们将看到相应的404 页面,但URL 不会改变(他们不会被重定向到错误页面)。
我无法实现这个想法
这就是我遇到问题的地方。如果用户输入http://example.com/asdf-,他们会被跳转到通用 404 页面。我想要做的是保留 URL(即:不重定向到任何其他页面),而只是显示“NotFound”视图并将HttpStatusCode.NotFound 推送到客户端。
例如,只需访问https://stackoverflow.com/asdf,您将看到自定义 404 页面并看到完整的 URL。
显然我错过了一些东西,但我无法弄清楚。由于“asdf”实际上并不指向任何控制器,因此我的基本控制器类没有启动,所以我无法在其中的“HandleError”过滤器中执行此操作。
提前感谢您的帮助。
注意:我绝对不想将用户重定向到 404 页面。我希望他们留在现有的 URL,我希望 MVC 将 404 VIEW 推送给用户。
编辑:
我也尝试了以下方法,但无济于事。
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.RouteExistingFiles = False
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.IgnoreRoute("Assets/{*pathInfo}")
routes.IgnoreRoute("{*robotstxt}", New With {.robotstxt = "(.*/)?robots.txt(/.*)?"})
routes.AddCombresRoute("Combres")
''# MapRoute allows for a dynamic UserDetails ID
routes.MapRouteLowercase("UserProfile", _
"Users/{id}/{slug}", _
New With {.controller = "Users", .action = "Details", .slug = UrlParameter.Optional}, _
New With {.id = "\d+"} _
)
''# Default Catch All Valid Routes
routes.MapRouteLowercase( _
"Default", _
"{controller}/{action}/{id}/{slug}", _
New With {.controller = "Events", .action = "Index", .id = UrlParameter.Optional, .slug = UrlParameter.Optional} _
)
''# Catch All InValid (NotFound) Routes
routes.MapRoute( _
"NotFound", _
"{*url}", _
New With {.controller = "Error", .action = "NotFound"})
End Sub
我的“未找到”路线什么也没做。
【问题讨论】:
标签: asp.net asp.net-mvc-2 routing http-status-code-404 handleerror