通过路由重定向到更具体的 URL
本文关键字:URL 路由 重定向 | 更新日期: 2023-09-27 18:31:07
我在项目中使用以下路由
routes.MapRoute(
"ProductRoute", // Route name
"product/{id}/{title}", // URL with parameters
new { controller = "product", action = "Index", id = UrlParameter.Optional }, // Parameters defaults
new[] { "PriceCompare.Controllers" }
);
手头的问题是 url 的显示方式。可以通过以下任一方式访问 URL:
- http://mywebsite.com/product/22/full-title
- http://mywebsite.com/product/22/half
- http://mywebsite.com/product/22/
一切都很好,因为所有这些URL都重定向到所需的位置。但是,我认为即使有人使用第二种或第三种方法,浏览器中的返回 URL 也应该显示第一个 URI。
就像StackOverflow一样。例如,如果您访问以下网址
stackoverflow.com/questions/734249/,您的浏览器地址将在浏览器 stackoverflow.com/questions/734249/asp-net-mvc-url-routing-with-multiple-route-values 中显示完整的URL
如何实现这一点?
您可以实现自己的Route
,也可以在操作中执行以下操作:
public ActionResult Index(int? id, string title = null)
{
if (String.IsNullOrWhiteSpace(title))
{
var product = // load product
return Redirect(Url.Action("Index", "Product",
new { id = id, title = product.Title }));
}
// your code
}