如何将 /Home 301 重定向到 root?
这是我在 Global.asax 中删除 /Home 的路线:
routes.MapRoute("Root", "{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我需要设置 301 重定向,因为有人链接到 /Home 并且他们收到了 404。
那么我该如何设置 301 呢?
我检查了路线的设置方式,它正在“Home”控制器中寻找“Home”操作方法。
显然我可以补充:
public ActionResult Home() {
Response.Status = "301 Moved Permanently";
Response.RedirectLocation = "/";
Response.End();
return Redirect("~/");
}
但是,必须有更好的方法来做到这一点,对吧?
Here is my route in Global.asax to remove /Home:
routes.MapRoute("Root", "{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Well I need to setup a 301 redirect because someone linked to /Home and they're getting a 404.
So how do I setup the 301?
I checked the way the route was setting up and it is looking for a "Home" action method in the "Home" controller.
So obviously I could add:
public ActionResult Home() {
Response.Status = "301 Moved Permanently";
Response.RedirectLocation = "/";
Response.End();
return Redirect("~/");
}
However, there's gotta be a better way of doing this right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你想允许这个URL,你可以做
但是你想要重定向,它确实最有意义,所以...
你可以做的另一件事是创建另一个控制器Redirector和一个action Home。
然后将路由设置为:
请记住将路由添加到路由的顶部,这样通用路由就不会匹配。
更新:
您可以做的另一件事是将其添加到路线末尾:
但这仍然不是重定向。因此,可以将重定向器更改为通用...
然后路由(现在应该位于所有路由的底部)将是:
因此,它将尝试重定向到具有相同名称的控制器的 Index 操作作为/名称。明显的限制是操作的名称和传递参数。您可以在其之上开始构建。
If you want to allow this URL, you can do
But you want redirection, and it does make most sense, so...
Another thing you can do is create another controller Redirector and an action Home.
Then you set the routes as:
Remember to add the route at the top of your routes so that the generic routes don't match instead.
Update:
Another thing you can do is add this to the end of your routes:
But this is not redirect still. So, can change the Redirector to be generic as...
Then the route (which should be now at the bottom of all routes) will be:
So, it'll try to redirect to the Index action of a controller with the same name as /name. Obvious limitation is the name of the action and passing parameters. You can start building on top of it.