gpt4 book ai didi

c# - 使用 Http.RouteAttribute 路由可选参数

转载 作者:太空宇宙 更新时间:2023-11-03 22:38:40 25 4
gpt4 key购买 nike

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

[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 是可选的,将与 ? 一起添加。需要的参数dateFromdateTo会加上/

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

/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}")]

但它们都不起作用。当我删除可选参数时它起作用了,但我需要那些可选参数。

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

最佳答案

让可选参数在action方法中可选

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

关于c# - 使用 Http.RouteAttribute 路由可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com