如何在 asp.net core 中创建具有多个可选字符串参数的路由?

问题描述

我有一个应用程序是在 asp.net core 5/.Net 5 框架之上编写的。我需要创建一个灵活的路由来绑定多个字符串参数。

例如,路线看起来像这样

/homes-for-sale-in-los-angeles-100/0-5000_price/condo,apartment_type/0-5_beds/0-4_baths/2_page

在上面的 URL 中,唯一需要的部分是 /homes-for-sale-in-los-angeles-100los-angeles 是城市名称,100 是 ID。其余的只是参数。 0-5000_price 表示我想将值 0-5000 绑定到名为 price 的参数。

并非总是提供所有参数。下面是同一条路线的一些不同形状

/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

这是我所做的

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

public class SearchViewModel 
{
    [Required]
    public int? Id { get; set; }
    
    public string City { get; set; }

    public string Price { get; set; }

    public string Type { get; set; }

    public string Beds { get; set; }

    public string Baths { get; set; }

    public int Page { get; set; }
}

如何创建允许多个可选参数并正确绑定它们的路由?

解决方法

使用这样的路由定义将使其捕获您提供的所有路由:

[Route("homes-for-sale-in-{city}-{id}/{**catchAll}")]
[HttpGet]
public async Task<IActionResult> City(string city,string id,string catchAll)
{
  // Here you will parse the catchAll and extract the parameters        
  await Task.Delay(100);
  return this.Ok(catchAll);
}

另请注意,不能将 catchAll 参数设为可选。因此,像 /homes-for-sale-in-los-angeles-100/ 这样的请求将导致 404。

相关问答

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