我目前有一个继承自System.Web.Mvc.Controller
. 在那个类上,我有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的内容(其中 userID 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
我的“未找到”路线什么也没做。