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

标签 c# asp.net-web-api asp.net-mvc-routing asp.net-web-api-routing

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

[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/

相关文章:

c# - C# 中的无限数字

c# - 如何从 Controller 触发弹出确认

javascript - 在特定设置中未调用 WebApi Controller 中的 SignalR 方法

linq - ASP.NET Web API GET 方法 : Passing multiple values for single parameter

asp.net-mvc - ASP.NET MVC3 无法解析 jQuery $.ajax() 发送的列表类型的 URL 参数

asp.net-mvc - asp.NET : Unknown length MVC paths

iis-6 - Asp.net MVC 应用程序中的虚拟目录应用程序

c# - WPF 和外部 CSS 文件

javascript - 如何在html中显示多个json结果

c# - 有条件的 DEBUG - 它是否仍然编译成 RELEASE 代码?