【问题标题】:How can I redirect to "page not found" with MVC3?如何使用 MVC3 重定向到“找不到页面”?
【发布时间】:2011-10-16 12:15:15
【问题描述】:

我在 Google 中有一些链接,现在我不再期望它们可以工作了。所有链接如下所示:

www.abc.com/xx/que=xxxxxxxxxxx

x 可以是任何东西。

谁能告诉我如何设置一个路由和控制器操作来返回 404 给谷歌?我想我需要使用包含“que”的掩码进行设置,但我不太确定如何执行此操作。

【问题讨论】:

    标签: asp.net-mvc model-view-controller asp.net-mvc-3 asp.net-mvc-routing


    【解决方案1】:

    添加一条新路线到您的 global.asax 的 顶部。这将使用正则表达式捕获 xx/que={anything} 形式的请求来定义“que”参数。

    routes.MapRoute(
        "PageNotFound", 
        "xx/{que}",
        new { controller = "Error", action = "NotFound" },
        new { que = "que=.*" });
    

    这也假设您在 /Views/Error/ 目录中有一个 ErrorController 和动作 NotFound 和名为 NotFound.aspx 的相应视图。

    public class ErrorController : Controller
    {
        public ActionResult NotFound()
        {
            Response.StatusCode = 404;
            return View();
        }
    }
    

    【讨论】:

    • 是否有类似 return RedirectPermanent 的等价物可以用来代替返回错误视图?
    • @Timothy 当然只返回 RedirectPermanent(string url) 而不是 NotFound 视图。所以如果你想重定向到谷歌,你可以做return RedirectPermanent("http://www.google.com");
    • 对不起,大卫。我没有正确表达我的问题。我想知道是否有一种方法可以返回 404 错误而无需转到 NotFound.aspx 之类的另一个视图?
    • @Timothy 如果你真的想要 404,你可以throw new HttpException(404, "Your error message");,但你应该从你的网站返回一些内容。因此,使用我的答案并将 Response.StatusCode 设置为 404(我将编辑我的答案)这将提供更好的用户体验。
    猜你喜欢
    • 2020-10-03
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2013-03-31
    • 2012-06-22
    • 2014-01-14
    • 1970-01-01
    相关资源
    最近更新 更多