C# 如何在asp.net core中使用多个可选字符串参数创建路由?

C# 如何在asp.net core中使用多个可选字符串参数创建路由?,c#,asp.net-core,asp.net-core-mvc,.net-5,asp.net5,C#,Asp.net Core,Asp.net Core Mvc,.net 5,Asp.net5,我有一个应用程序,它是在asp.net core 5/.net 5 framework之上编写的。我需要创建一个灵活的路由来绑定多个字符串参数 例如,路线将如下所示 /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是

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

例如,路线将如下所示

/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-100
los 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(“/HomesForSaleByCity中出售的房屋-{city}-{id:int}.{filter?}/{page:int?}”,Name=“HomesForSaleByCity”)]
公共异步任务显示(SearchViewModel viewModel)
{
返回视图();
}
公共类SearchViewModel
{
[必需]
公共int?Id{get;set;}
公共字符串City{get;set;}
公共字符串Price{get;set;}
公共字符串类型{get;set;}
公共字符串{get;set;}
公共字符串浴室{get;set;}
公共整型页{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);
}
[路线(“在{city}-{id}/{**catchAll}出售的房屋”)]
[HttpGet]
公共异步任务城市(字符串城市、字符串id、字符串catchAll)
{
//在这里,您将解析catchAll并提取参数
等待任务。延迟(100);
返回这个。Ok(catchAll);
}

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

在这种情况下,使用查询字符串参数更合适。你也可以像这样继续使用
SearchViewModel
公共异步任务显示([FromQuery]SearchViewModel viewModel)请参见以下内容:@Eldar查询参数不利于搜索引擎优化。问题中的URL将提供一个自然的URL,即SEOfriendly@jdweng我不认为有多条路线是可行的,因为这些过滤器有很多组合。例如,
价格、类型和床位
价格和床位
床位和类型
。。。。我正在寻找一个更健壮的解决方案,它只需解析所有这些参数并填充available@Jay然后,您需要一个类似于捕获所有路由的
,以及路由参数的正则表达式处理。喜欢它适用于旧的asp.net,但它可以为您提供它不起作用的想法。Its正在抛出以下错误
RoutePatterneException:包含多个节(如文字节或参数)的路径段不能包含一个catch-all参数。
实际上此代码有效!非常感谢你!!