ASP.NET MVC – 如何抛出与StackOverflow类似的404页面

前端之家收集整理的这篇文章主要介绍了ASP.NET MVC – 如何抛出与StackOverflow类似的404页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前有一个继承自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(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

我的“NotFound”路线什么也没做.

解决方法

找到我的答案 on my other SO question.非常感谢 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,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));
        }
    }
}
原文链接:https://www.f2er.com/aspnet/249484.html

猜你在找的asp.Net相关文章