StackOverflow 类似路由重定向

发布于 2024-12-15 07:09:57 字数 881 浏览 0 评论 0原文

我正在创建一个网站,其路由与 SO 非常相似,因为它们是:

posts/{id}/{title}

我想复制功能,对于任何给定的路由 X

任何以 /posts/{id 开头的内容} 并且标题不正确,被重新路由到 /posts/{id}/{title}

在控制器中这样做似乎很尴尬,但在路由级别这样做似乎更糟糕。

我想控制器是最好的选择。

public ActionResult Display(long id, string title)
{
    // try and find post
    // if post is null, error

    // if post.title != title, permanent redirect to correct title
    if (title != "correct-ness-ly")
    {
        return RedirectToActionPermanent("Display", new { id, title = "correct-ness-ly" });
    }

    // permanent redirect if name doesn't match
    return new ContentResult { Content = "display post-id : {0}, {1}".FormatWith(id, title) }; // found or not
}

有没有一种“更干净”的方法来实现这一点?

更新我刚刚意识到这会让我“丢失”可能存在的任何查询字符串值。除了必须以声明方式传递每个操作参数之外。

I'm creating a website that has routes pretty similar to SO, in that they are:

posts/{id}/{title}

I want to copy the functionality where for any given route X

anything that starts with /posts/{id} and has an incorrect title, gets rerouted to /posts/{id}/{title}

doing so in the controller seems pretty awkward, but doing it at routing level seems even worse.

I guess the controller would be the way to go.

public ActionResult Display(long id, string title)
{
    // try and find post
    // if post is null, error

    // if post.title != title, permanent redirect to correct title
    if (title != "correct-ness-ly")
    {
        return RedirectToActionPermanent("Display", new { id, title = "correct-ness-ly" });
    }

    // permanent redirect if name doesn't match
    return new ContentResult { Content = "display post-id : {0}, {1}".FormatWith(id, title) }; // found or not
}

Is there a "cleaner" way to accomplish this?

Update I just realized this makes me "lose" any querystring values there might be. Besides having to declaratively pass each action argument.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗藏城府 2024-12-22 07:09:57

您没有指定您使用的 IIS 版本。但对于 7+,您可以使用重定向模块

对于 IIS 6,有多个可以使用的第三方 URL 重定向模块。

You didn't specify what version of IIS you are using. But for 7+ you can use the redirect module.

For IIS 6 there were several third party URL Redirect modules that could be used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文