首页 > 解决方案 > 来自路由和查询字符串的 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();
}

标签: asp.netasp.net-core-webapi

解决方案


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。


推荐阅读