如何解决如何在 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-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("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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。