【问题标题】:How to set up routing so that Index does show?如何设置路由以便索引显示?
【发布时间】:2013-07-17 20:33:17
【问题描述】:

所以我知道如果你在多个 url 上有相同的内容,谷歌会惩罚一个网站......不幸的是,在 MVC 中这太常见了,我可以拥有 example.com/example.com/Home/example.com/Home/Index,并且所有三个 url 都会带我到同一页面...所以我如何确保每当Index 在网址中时,它会在没有Index 的情况下重定向到相同的页面,当然也与Home 相同

【问题讨论】:

标签: c# .net asp.net-mvc-4 routing


【解决方案1】:

也许this little library 可能对你有用。 这个库在你的情况下不是很方便,但它应该可以工作。

var route = routes.MapRoute(name: "Default",
                            url: "{controller}/{action}/{id}",
                            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

routes.Redirect(r => r.MapRoute("home_index", "/home/index")).To(route);
routes.Redirect(r => r.MapRoute("home", "/home")).To(route);

【讨论】:

  • 您几乎得到了已接受的答案,但我找到了一种不依赖外部库的方法...
【解决方案2】:

对于像索引这样的默认页面,我处理这个问题的方法是只为其中一个页面创建一个显式路由。 IE。 "example.com/People" 将是 People/Index 的路由,在 url "/example.com/People/Index" 处将没有有效页面。

Home 示例的独特之处在于它可能具有三个不同的 URL。同样在这种情况下,我只需为该索引操作创建一个“example.com”的路由,而不支持其他两个 url。换句话说,您永远不会链接到其他形式的 URL,因此它们的缺失绝不会导致问题。

我们使用一个名为 AttributeRouting 的 Nuget 包来支持这一点。当您为页面指定 GET 路由时,它会覆盖 MVC 的默认值。

使用 AttributeRouting 通常您会将索引映射到 [GET("")] 但对于 Home 的特殊情况,您还希望支持省略控制器名称的根 URL,我认为您还需要添加一个附加属性IsAbsoluteUrl:

public class HomeController : BaseController
{
     [GET("")]
     [GET("", IsAbsoluteUrl = true)]
     public ActionResult Index()
     {...

【讨论】:

  • 一个关于如何为 Home、Home/Index 设置路由的示例,我们可以一起使用您的 People 示例,这将是最有帮助的...
  • @SerjSagan 添加了一个示例
  • 也许你误解了我的问题......这个方法1需要一个外部库,2它不起作用......它仍然允许我去Home/Home/Index/跨度>
【解决方案3】:

所以我找到了一种不需要任何外部库的方法......

在我的RouteConfig 中,我必须在顶部添加这两条路线,就在IgnoreRoute 下方

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

        routes.MapRoute(
            "Index",
            "{action}/Index",
            new { controller = "Redirect", action = "Home" }
        );

然后我必须创建一个名为 Redirect 的新 Controller 并为我的其他每个 Controllers 创建一个方法,如下所示:

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

    public ActionResult News()
    {
        return RedirectPermanent("~/News/");
    }

    public ActionResult ContactUs()
    {
        return RedirectPermanent("~/ContactUs/");
    }

    // A method for each of my Controllers
}

就是这样,现在我的网站看起来合法了。我的 URL 中不再有主页,不再有索引,这当然有不能接受任何 Index 方法的参数的限制 Controllers 虽然如果真的有必要,你应该能够调整这可以实现你想要的。

仅供参考,如果您想将参数传递给您的索引操作,那么您可以像这样添加第三条路线:

 routes.MapRoute(
            name: "ContactUs",
            url: "ContactUs/{id}/{action}",
            defaults: new { controller = "ContactUs", action = "Index", id = UrlParameter.Optional }
        );

这将创建一个这样的 URL:/ContactUs/14

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2018-09-12
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多