如何创建处理丢失的中间参数的路由属性?
How to create a route attribute which handles missing middle parameters?
如果我有下面的代码并且当 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 ...
}
}
示例 URL:
http://...api/customers
http://...api/customers?status=valid
http://...api/customers?firstname=john&status=active
http://...api/customers?firstname=john
如果我有下面的代码并且当 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 ...
}
}
示例 URL:
http://...api/customers
http://...api/customers?status=valid
http://...api/customers?firstname=john&status=active
http://...api/customers?firstname=john