ASP.NET MVC 6(ASP.NET Core或ASP.NET5)中的友好URL

化学性

在我的网站上,我有这样的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 (GitHub上的官方项目)中的路由的信息,但是我还不清楚如何做。

谢谢!!

马尔辛·扎布基(Marcin Zablocki)

要在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/zh/latest/fundamentals/routing.html?highlight= routing

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章