ASP.NET MVC - 如何抛出类似于StackOverflow上的404页面

Cha*_*ell 12 asp.net routing handleerror http-status-code-404 asp.net-mvc-2

我目前有一个继承自的BaseController类System.Web.Mvc.Controller.在那个类上我有HandleError属性,将用户重定向到"500 - 糟糕,我们搞砸了"页面.目前正在按预期工作.

这个工作

<HandleError()> _
Public Class BaseController : Inherits System.Web.Mvc.Controller

''# do stuff
End Class
Run Code Online (Sandbox Code Playgroud)

我还有我的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
Run Code Online (Sandbox Code Playgroud)

再次,这很好用.如果用户输入类似http://example.com/user/999(其中不存在userID 999)的内容,他们将看到相应的404页面,但URL不会更改(它们不会重定向到错误页).

我无法理解这个想法

这是我遇到问题的地方.如果用户输入http://example.com/asdf-他们将被踢到通用404页面.我想要做的是保留URL(IE:不重定向到任何其他页面),但只需显示"NotFound"视图以及推HttpStatusCode.NotFound送到客户端.

例如,只需访问https://stackoverflow.com/asdf,您将在其中看到自定义404页面并查看保留的网址.

显然我错过了一些东西,但我无法弄清楚.由于"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
Run Code Online (Sandbox Code Playgroud)

我的"NotFound"路线什么也没做.

Cha*_*ell 9

在我的另一个问题上找到了答案.非常感谢Anh-Kiet Ngo的解决方案.

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();

    // A good location for any error logging, otherwise, do it inside of the error controller.

    Response.Clear();
    HttpException httpException = exception as HttpException;
    RouteData routeData = new RouteData();
    routeData.Values.Add("controller", "YourErrorController");

    if (httpException != null)
    {
        if (httpException.GetHttpCode() == 404)
        {
            routeData.Values.Add("action", "YourErrorAction");

            // We can pass the exception to the Action as well, something like
            // routeData.Values.Add("error", exception);

            // Clear the error, otherwise, we will always get the default error page.
            Server.ClearError();

            // Call the controller with the route
            IController errorController = new ApplicationName.Controllers.YourErrorController();
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的解决方案,但是在errorController.Execute之前(新的RequestContext(new HttpContextWrapper(Context),routeData)); 被调用,这行需要添加Response.StatusCode = 404; 如果未添加此行,则无论为用户呈现什么,页面响应仍为200. (4认同)