You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core查询参数使用错误致站点故障,请求排查

问题分析与修复方案

核心错误点

  • 路由定义违规:你在[Route]属性里错误地将查询参数(from、to)写入路径模板,还误用了?和/to这类不符合ASP.NET Core路由规则的语法。路由模板仅负责定义URL的路径部分,查询参数无需在此声明,框架会自动识别[FromQuery]标记的参数。
  • 可选参数未配置:from和to是值类型DateTime,默认会被判定为必填参数,不符合你“可选过滤器”的需求,需改为可空值类型。

修正后的代码

[HttpGet]
[Route("/v2/config/get_metadata/{name}")]
[ValidateModelState]
[SwaggerOperation("GetMetadata")]
[SwaggerResponse(statusCode: 200, type: typeof(Metadata), description: "successful operation")]
public virtual IActionResult GetMetadata([FromRoute][Required] string name,
  [FromQuery] DateTime? from, [FromQuery] DateTime? to)
{
  //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
  // return StatusCode(200, default(Dataset));

  //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
  // return StatusCode(400);

  string exampleJson = null;
  exampleJson = "{}";
  exampleJson = "";

  var example = exampleJson != null
  ? JsonConvert.DeserializeObject<Metadata>(exampleJson)
  : default(Metadata);
  //TODO: Change the data returned
  return new ObjectResult(example);
}

关键修改说明

  1. 简化路由模板:将路由调整为/v2/config/get_metadata/{name},仅保留路径参数name。调用接口时,查询参数通过URL后缀传递,格式示例:/v2/config/get_metadata/testName?from=2024-01-01&to=2024-06-01。
  2. 配置可选参数:将DateTime from和DateTime to改为DateTime? from和DateTime? to,允许用户不传递这两个参数。如果需要默认值,可直接在参数上赋值,比如[FromQuery] DateTime? from = default。

内容的提问来源于stack exchange,提问作者bob123123123123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:52:32