我想执行GET请求,例如https://localhost:12345/api/employees/1/calendar/2018/2019?checkHistoricalFlag=true
我已经在控制器中创建了此方法,该方法可以按预期工作:
[AllowAnonymous]
[HttpGet("/api/employees/{clockNumber:int}/calendar/{yearFrom:int}/{yearTo:int}")]
public IActionResult Get(int clockNumber, int yearFrom, int yearTo, bool checkHistoricalFlag = false)
{
return Ok();
}
但是我更喜欢使用以下视图模型:
public class DetailsQuery
{
[Required]
public int? ClockNumber { get; set; }
[Required]
public int? YearFrom { get; set; }
[Required]
public int? YearTo { get; set; }
public bool CheckHistoricalFlag { get; set; } = false;
}
这绑定了路由参数,但忽略了查询字符串中的“ checkHistoricalFlag”:
[AllowAnonymous]
[HttpGet("/api/employees/{clockNumber:int}/calendar/{yearFrom:int}/{yearTo:int}")]
public IActionResult Get([FromRoute]DetailsQuery query)
{
return Ok();
}
删除[FromRoute]会导致415“不支持的媒体类型”错误。
是否可以将路由参数和查询字符串值都绑定到一个视图模型,还是需要分别指定查询字符串值?
[AllowAnonymous]
[HttpGet("/api/employees/{clockNumber:int}/calendar/{yearFrom:int}/{yearTo:int}")]
public IActionResult Get([FromRoute]DetailsQuery query, bool checkHistoricalFlag = false)
{
return Ok();
}
答案 0 :(得分:1)
Imantas的评论指出,我想在视图模型上使用[FromQuery],如下所示:
public class DetailsQuery
{
[Required]
public int? ClockNumber { get; set; }
[Required]
public int? YearFrom { get; set; }
[Required]
public int? YearTo { get; set; }
[FromQuery]
public bool CheckHistoricalFlag { get; set; } = false;
}
控制器方法现在为:
[AllowAnonymous]
[HttpGet("/api/employees/{clockNumber:int}/calendar/{yearFrom:int}/{yearTo:int}")]
public ActionResult Get([FromRoute]DetailsQuery query)
{
return Ok();
}
按预期工作。
感谢指针Imantas。