gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:55:17 25 4
gpt4 key购买 nike

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

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

Controller 返回一个包含产品详细信息的 View 。

我的产品类DTO(只是重要领域)

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

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

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

实现它的最佳方法是什么?

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

谢谢!!

最佳答案

要在 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

关于c# - ASP.NET MVC 6(ASP.NET Core 或 ASP.NET5)中的友好 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35943643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com