【问题标题】:Friendly URLs in ASP.NET MVC 6 (ASP.NET Core or ASP.NET5)ASP.NET MVC 6(ASP.NET Core 或 ASP.NET5)中的友好 URL
【发布时间】:2016-06-26 21:36:27
【问题描述】:

在我的网站中,我有这样的 URL:

https://www.mywebsite.com/View/Index/{MongoDbId}

控制器返回一个带有产品详细信息的视图。

我的产品类 DTO(只是重要的字段)

public class ProductDto
{
   public string Id {get; set;}
   public string Name {get; set;}
}

此时我有一个名为 View 的控制器和一个处理请求的 Index 方法,但我想要这样的东西:

https://www.mywebsite.com/v/56b8b8801561e80c245a165c/amazing-product-name

实现这一点的最佳方法是什么?

我已经阅读了 ASP.NET Core (official project on GitHub) 中的路由,但我不太清楚该怎么做。

谢谢!!

【问题讨论】:

  • 如果您希望您的网址 100% 对 SEO 友好(网址中没有 ID),最好的方法是使用 data-driven routing by implementing IRouter
  • 但是我有大约 80000 项,还有更多……我可以在没有性能问题的情况下使用它吗?
  • 而在这一刻...我没有 URL 字段...
  • 我只是说除了接受的答案之外还有其他选择。使用该解决方案您肯定会获得更好的性能,但您的网站在 SERP 中的排名可能不如 URL 中没有 ID 的网站。没有适合所有人的万能解决方案,您需要根据性能还是 SEO 更重要来决定。当然,使用缓存时(如答案所示)性能将取决于您有多少可用内存以及您根据 URL 流行度将路由实例优化到不同缓存中的程度。

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

要在 ASP.NET Core 中全局配置路由,请使用 Startup.cs 中的扩展方法:

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

在您的情况下,对于 url: https://www.mywebsite.com/v/56b8b8801561e80c245a165c/amazing-product-name 它可能看起来像这样:

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "v/{customId}/{customName}",
                    defaults : new{controller = "View", action = "Index"});
            });

然后您的操作应按如下方式处理 customIdcustomName 参数:

public IActionResult Index(string customId, string customName)
{
   //customId will be 56b8b8801561e80c245a165c
   //customName will be amazing-product-name
}

有关 ASP.NET Core 中路由的更多信息,请访问: http://docs.asp.net/en/latest/fundamentals/routing.html?highlight=routing

【讨论】:

【解决方案2】:

您可以使用路由在 .NET 框架中创建虚 URL。 attribute-routing-in-asp-net-mvc-5

基本概述是您可以像这样装饰您的操作:

[Route("Album/Edit/{id:int}")] public ActionResult Edit(int id)

【讨论】:

  • 您的示例来自 WebForms,在这种情况下无效。还有...名称 param 会发生什么?
  • @chemitaxis:它是为 MVC 设计的。
  • 示例大致来自 MVA 课程 Introduction to ASP.NET MVC
  • 如何在 ASP.NET Core 中注册新路由器?
猜你喜欢
  • 2013-02-14
  • 2012-09-16
  • 1970-01-01
  • 2021-10-27
  • 2011-04-06
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
相关资源
最近更新 更多