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

How to create route with multiple optional string parameters in 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.