简体   繁体   English

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

[英]Query string parameter with WebAPI routing

If I have an endpoint 如果我有端点

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

I can make the calls like this: 我可以这样打电话:

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

But what if I want to send a date as part of the query string? 但是,如果要发送日期作为查询字符串的一部分怎么办?

For example I want to send the following: http://localhost/customers/1234-5678/orders?01-15-2019 例如,我想发送以下内容: http:// localhost / customers / 1234-5678 / orders?01-15-2019

How can I set my endpoint? 如何设置端点?

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

In a [HttpPatch] type of request, only primitive types are can be used as query strings. [HttpPatch]类型的请求中,仅原始类型可用作查询字符串。 And DateTime is not a primitive type. 而且DateTime不是原始类型。

As your example suggests that you need to pass just the date part to the query string, therefore, you can use string datatype instead and convert it to date inside the action method. 如您的示例所示,您只需要将date部分传递给查询字符串,因此,您可以改用string数据类型,然后在action方法中将其转换为日期。 Something like this: 像这样:

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
}

You could modify your route attribute to the following: 您可以将route属性修改为以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM