如何创建处理缺少中间参数的路由属性?



如果我有下面的代码,并且当 url 中缺少名字时,我会收到 404 错误。请参阅下面的第一个示例。我不确定为什么在这种情况下,当属性名称在 url 中时路由不起作用,值是否有占位符。我的解决方案是创建另一条路由并使用另一种 url 格式,但这需要做更多的工作。如果我有很多参数,而中间的一些参数缺少它们的值,难道没有一条路由可以处理所有实例吗? 如何创建可以处理以下示例中的四种组合的单个路由?两者都不见了。两者都存在。其中一个失踪了。

[HttpGet]
[Route("getcustomer/firstname/{firstname?}/status/{status?}")]      
public IHttpActionResult GetCustomer(string firstname = null, string status = null)
{
... some code ...
}
**Example URLs:**  
http://.../getcustomer/firstname//status/valid"       causes 404
http://.../getcustomer/firstname/john/status/active"   good
http://.../getcustomer/firstname/john/status/"        good

这是设计使然。您可能需要创建另一个操作来允许这样做。同样在如何构建框架方面。端段应该是可选的。

你需要重新考虑你的设计。

例如

[RoutePrefix("api/customers")]
public class CustomersController : ApiController {
[HttpGet]
[Route("")] // Matches GET  api/customers
public IHttpActionResult GetCustomer(string firstname = null, string status = null) {
... some code ...
}
}

示例网址:
http://...api/customershttp://...api/customers?status=valid
http://...api/customers?firstname=john&status=active

http://...api/customers?firstname=john

最新更新