使用 Http.RouteAttribute 路由可选参数

Routing optional parameters with Http.RouteAttribute

我有一个带有两个必需参数和一些可选参数的操作:

[HttpGet]
public IHttpActionResult GetUsers(DateTime dateFrom, DateTime dateTo, string zipcode, int? countryId)
{
    using (DataHandler handler = new DataHandler())
        return Ok(handler.GetUsers(dateFrom, dateTo).ToList());
}

我想要一个像这样的url:

/api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002&countryId=4

zipcodecountryId 是可选的,将与 ?-thingy 一起添加。所需参数dateFromdateTo将添加/

所以下面的 urls 也应该是可能的:

/api/getusers/2018-12-03T07:30/2018-12-03T12:45?countryId=4
/api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002
/api/getusers/2018-12-03T07:30/2018-12-03T12:45

我尝试了一些路由,比如

[Route("getusers/{dateFrom}/{dateTo}")]
[Route("getusers/{dateFrom}/{dateTo}*")]
[Route("getusers/{dateFrom}/{dateTo}**")]
[Route("getusers/{dateFrom}/{dateTo}?zipcode={zipcode}&countryId={countryId}")]

但其中 none 正在运行。 当我删除可选参数时它起作用了,但我需要那些可选参数。

知道如何完成这项工作吗?

在操作方法中将可选参数设置为可选

If a route parameter is optional, you must define a default value for the method parameter.

//GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45?countryId=4
//GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002
//GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45
[HttpGet]
[Route("getusers/{dateFrom:datetime}/{dateTo:datetime}")]
public IHttpActionResult GetUsers(DateTime dateFrom, DateTime dateTo, string zipcode = null, int? countryId = null) {
    using (DataHandler handler = new DataHandler())
        return Ok(handler.GetUsers(dateFrom, dateTo).ToList());
}

引用Attribute Routing in ASP.NET Web API 2