我如何301重定向/家庭为根? [英] How do I 301 redirect /Home to root?

查看:114
本文介绍了我如何301重定向/家庭为根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在Global.asax中路由删除/首页:

Here is my route in Global.asax to remove /Home:

    routes.MapRoute("Root", "{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );

好吧,我需要设置一个301重定向,因为有人链接到/家庭和他们得到一个404。

Well I need to setup a 301 redirect because someone linked to /Home and they're getting a 404.

因此​​,我怎么设置的301?

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?

推荐答案

如果你想允许这个网址,你可以做

If you want to allow this URL, you can do

routes.MapRoute("Root", "Home",
     new { controller = "Home", action = "Index", id = UrlParameter.Optional });

但是你要重定向,并且它使最有意义,所以......

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.

public class RedirectorController : Controller
{
    public ActionResult Home()
    {
        return RedirectPermanent("~/");
    }
}

然后,设置路线为:

Then you set the routes as:

routes.MapRoute("Root", "Home",
        new { controller = "Redirector", action = "Home"});

请记住,在你的路由顶部添加路由,这样通用的路由不匹配,而不是

Remember to add the route at the top of your routes so that the generic routes don't match instead.

更新:

你可以做的另一件事是添加到您的路线的结尾:

Another thing you can do is add this to the end of your routes:

routes.MapRoute("Root", "{controller}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional });

但是,这是不是还重定向。因此,可以改变重定向器是通用的...

But this is not redirect still. So, can change the Redirector to be generic as...

public class RedirectorController : Controller
{
    public ActionResult Redirect(string controllerName, string actionName)
    {
        return RedirectToActionPermanent(actionName, controllerName);
    }
}

然后,路线(其应在所有路线的底部现在定)将是:

Then the route (which should be now at the bottom of all routes) will be:

routes.MapRoute("Root", "{controllerName}",
        new { controller = "Redirector", action = "Redirect", 
              controllerName = "Home", actionName = "Index" });

因此​​,它会尝试重定向到具有相同的名称/姓名控制器的Index操作。明显的限制是行动,传递参数的名称。你可以开始建立在它之上。

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.

这篇关于我如何301重定向/家庭为根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆