我正在开发一个ASP.NET MVC网站。在我的网站上,我在RouteConfig中进行url重写以获得更好的SEO。但我遇到了问题。问题在于编码URL路由数据值。请参阅下面的方案。
我在RouteConfig中重写了一个URL,如下所示:
routes.MapRoute(
"",
"places/category/{categoryName}/{category}",
new { controller = "Item", action = "List", categoryName = "", category = 0 },
new string[] { "AyarDirectory.Web.Controllers" }
);
在我的HTML中,我创建了一个这样的锚链接:
<a href="@Url.Content("~/places/category/" + HttpUtility.UrlEncode(category.Name) + "/" + category.Id)">
Content
</a>
当我点击它时,如果名称在编码后不包含“+”,“%”等字符,它总是显示404.它在编码后不包含空格和/(因此没有像%和+这样的字符) ,它工作正常。
我在行动中抓住价值:
HttpUtility.UrlDecode(value)
为什么不工作?如何编码路径数据值?即使值包含空格,如果我不编码值,它工作正常。结果URL将是这样的空格。
http://localhost:50489/places/guest house/4
因此,如果我使用没有编码值,它的值包含“/”,它将是错误。为什么会发生这种情况?如何编码URL路由数据值?
您永远不应该将URL硬编码到您的应用程序中。使用路由(而不是URL重写)的全部意义在于它允许您将所有URL创建逻辑存储在一个位置(即路由表)。
路由不仅确保您具有可维护的URL,还提供了一种机制,可以自动对段进行URL编码。您应该使用Url.Content
,Html.ActionLink
或Html.RouteLink
来使用MVC构建您的URL,而不是使用Url.Action
。
@Html.ActionLink("Content", "List", "Item",
new { categoryName = category.Name, id = category.Id }, null)
如果您需要按名称调用特定路线,则可以使用Html.RouteLink
。
@Html.RouteLink("Content", "TheRoute", new {
controller = "Item",
action = "List",
categoryName = category.Name,
id = category.Id })
但是,您需要为您的路线命名。
routes.MapRoute(
"TheRoute",
"places/category/{categoryName}/{category}",
new { controller = "Item", action = "List", categoryName = "", category = 0 },
new string[] { "AyarDirectory.Web.Controllers" }
);
注意:您也可以在不提供路径名的情况下使用
RouteLink
。在这种情况下,它的工作方式类似于ActionLink
。如果您已经有一个包含路由值的RouteValueDictionary
实例并且只想构建指向这些路由值的超链接,那么这将非常有用。
如果您需要在锚标记内添加HTML,则可以使用Url.Action
。
<a href="@Url.Action("List", "Item", new { categoryName = category.Name, id = category.Id })">
HTML Content Here...
</a>