使用 vanityURL 在 MVC 站点上正确呈现 ActionLink

Correctly rendering ActionLinks on MVC site with vanityURL

我需要创建网站,其中 URL 模式允许个性化 URL,例如 www.mysite.com 会打开主门户。

www.mysite.com/customer1 带来为该客户定制的门户(相同的操作和控制器称为定制参数将从 URL 中提取)。

我希望前缀“/customer1/”始终保留在所有页面的 URL 中。

我有以下路线可以正常工作:

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

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

但是,当我在 vanityURL 上进入网站时 www.mysite.com/customer1 所有操作链接都呈现为 OK

<a href="/customer1/Home/Contact">Contact</a>

但是当我只输入 www.mysite.com 时,所有链接都呈现为:

<a href="//Home/Testimonials">Testimonials</a> 

而且我无法导航到任何地方。

如何在没有 companyurl 参数和额外的 / 的情况下让它们正确呈现?

假设我理解正确,试试这个(虽然检查它是否按预期工作):

  • 删除 {companyurl} 的默认值 - 这使得该路由的 "mandatory" (意味着它不会 "match" 你的 CompanyUrl 路由配置 如果不存在 并通过下一个配置,即 Default 配置)。

所以你的 "CompanyUrl" 路线:

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

第...