asp.net - 来自路由和查询字符串的 ASP.NET Core 模型绑定
问题描述
我想执行一个 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();
}
解决方案
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。
推荐阅读
- postgresql - 触发器:允许更新“除 foo 之外的任何列”
- c++ - 自动分配对象(链表节点)时出错,但不是动态分配
- servicestack - SqliteException:SQLite 错误 1:“SQL 变量太多”
- powerbi - 使用 LOOKUPVALUE 返回所有值,而不仅仅是匹配项
- javascript - 如何使用 es6 every 返回嵌套数组的布尔值?
- python - 将 Pandas DataFrames 与不同列中的键合并
- reverse-proxy - 反向代理背后的 Acumatica 导致 GetFile.ashx 出现问题
- python - 有没有办法每 x 秒运行一次函数?(每秒输出)
- python - 如何在 peewee 中使用 backref
- excel - 如果逻辑测试包含 5 < x < 7 之类的区间,我该如何格式化 IFS 语句?