使用WebAPI路由查询字符串参数

时间:2019-05-02 16:19:51

标签: c# asp.net-web-api

如果我有端点

public class OrdersController : ApiController
{
    [Route("customers/{customerId}/orders")]
    [HttpPatch]
    public IEnumerable<Order> UpdateOrdersByCustomer(int customerId) { ... }
}

我可以这样拨打电话:

http://localhost/customers/1/orders
http://localhost/customers/bob/orders
http://localhost/customers/1234-5678/orders

但是如果我想发送日期作为查询字符串的一部分怎么办?

例如,我要发送以下内容: http://localhost/customers/1234-5678/orders?01-15-2019

如何设置端点?

public class OrdersController : ApiController
{
    [Route("customers/{customerId}/orders")]
    [HttpPatch]
    public IEnumerable<Order> UpdateOrdersByCustomer(int customerId, DateTime? effectiveDate) { ... }
}

2 个答案:

答案 0 :(得分:1)

[HttpPatch]类型的请求中,仅primitive types可用作查询字符串。并且DateTime不是原始类型。

如您的示例所示,您只需将date部分传递给查询字符串,因此,您可以改用string数据类型并将其转换为action方法内的日期。像这样:

public IEnumerable<Order> UpdateOrdersByCustomer(int customerId, string effectiveDate)  //changed datatype of effectiveDate to string
{
    //converting string to DateTime? type
    DateTime? effDate = string.IsNullOrEmpty(effectiveDate) ? default(DateTime?) : DateTime.Parse(str);

    // do some logic with date obtained above
}

答案 1 :(得分:0)

您可以将route属性修改为以下内容:

public class OrdersController : ApiController
{
    [Route("customers/{customerId}/orders/{effectiveDate?}")]
    [HttpPost]
    public IEnumerable<Order> UpdateOrdersByCustomer(int customerId, DateTime? effectiveDate) { ... }
}