![](/img/trans.png)
[英].NET 6 - How to use Optional Route Parameters ASP.NET Core WEB API?
[英]How to create route with multiple optional string parameters in asp.net core?
我有一个写在 asp.net 核心 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。 它的rest只是参数。 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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.