Параметр строки запроса с маршрутизацией WebAPI - PullRequest
0 голосов
/ 02 мая 2019

Если у меня есть конечная точка

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 ]

1 голос
/ 05 мая 2019

В запросе типа [HttpPatch] в качестве строк запроса могут использоваться только типы примитивов . И DateTime не является примитивным типом.

Как показывает ваш пример, вам нужно передать только часть date в строку запроса, поэтому вы можете вместо этого использовать тип данных string и преобразовать его в дату в методе действия. Примерно так:

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
}
0 голосов
/ 02 мая 2019

Вы можете изменить свой атрибут маршрута следующим образом:

public class OrdersController : ApiController
{
    [Route("customers/{customerId}/orders/{effectiveDate?}")]
    [HttpPost]
    public IEnumerable<Order> UpdateOrdersByCustomer(int customerId, DateTime? effectiveDate) { ... }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...