StackOverflow 类似路由重定向
我正在创建一个网站,其路由与 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有指定您使用的 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.