创建匹配所有以 ASP.NET Core 中特定模式开头的 url 的路由模板

问题描述

我有一个基于 ASP.NET Core 5 / .NET 5 Framework 编写的应用程序。我需要创建一个路由模板,该模板将引导以 /homes-for-sale-in-{city}-{id:int} 开头的任何 URL 来定义控制器/操作。

以下是一些网址示例

/homes-for-sale-in-los-angeles-100/condo,apartment_type
/homes-for-sale-in-los-angeles-100/0-5000_price/10_page
/homes-for-sale-in-los-angeles-100/condo_type/0-5000_price/2_page
.... yes there are many more

我尝试了以下模式

[Route("/homes-for-sale-in-{city}-{id:int}{*.}",Name = "HomesForSaleByCity")]
public async Task<IActionResult> Display(string city,id? id)
{
    return View();
}

但我收到此错误:

RoutePatternException:包含多个部分(例如文字部分或参数)的路径段不能包含全能参数。

如何添加一个模式来重定向任何以模式开头的网址?

解决方法

我认为您需要在路由中使用正则表达式,并且可能会引用 this page 一次。

,

这成功了

[Route("/homes-for-sale-in-{city}-{id:int}/{**filters}",Name = "HomesForSaleByCity")]
public async Task<IActionResult> Display(string city,id? id,string filters = "")
{
    return View();
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...