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

如何在ASP.NET Core 6.0中实现JSON:API标准的多过滤参数GET接口

解决ASP.NET Core 6.0 API绑定JSON:API风格过滤参数的问题

问题根源

你用string? filter无法绑定filter[category]这类参数,是因为ASP.NET Core的模型绑定不会自动把这种键值对合并成单个字符串,需要对应的数据结构来接收这类嵌套格式的参数。

具体解决方案

方案1:用字典接收所有过滤参数

直接使用Dictionary<string, string>作为参数类型,ASP.NET Core会自动将所有filter[xxx]格式的键值对绑定到字典中:

[HttpGet("GetArticles")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<IContent>> GetArticles(
    int pageId, 
    int filterId, 
    Dictionary<string, string>? filter = null)
{
    // 示例:处理多值的category参数
    if (filter != null && filter.TryGetValue("category", out var categoryStr))
    {
        var categoryIds = categoryStr.Split(',').Select(int.Parse).ToList();
        // 后续业务逻辑处理
    }
    
    // 其他参数处理逻辑
    return Ok();
}

方案2:定义强类型过滤类(更规范)

如果过滤参数的字段是固定的,建议创建强类型类来接收,便于维护和参数验证:

// 自定义过滤参数类
public class ArticleFilter
{
    public string? Category { get; set; }
    public int? Author { get; set; }
    public int? Year { get; set; }
}

// 修改API端点方法
[HttpGet("GetArticles")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<IContent>> GetArticles(
    int pageId, 
    int filterId, 
    ArticleFilter? filter = null)
{
    // 处理多值分类参数
    List<int>? categoryIds = null;
    if (!string.IsNullOrEmpty(filter?.Category))
    {
        categoryIds = filter.Category.Split(',').Select(int.Parse).ToList();
    }
    
    // 使用filter.Author、filter.Year等参数
    return Ok();
}

额外说明

  • 对于filter[category]=1,2这类多值参数,需要手动按逗号拆分并转换类型,ASP.NET Core不会自动处理这种格式的拆分。
  • 若项目需要全局支持JSON:API参数格式,可通过配置MvcOptions调整模型绑定行为,但上述两种方案已能满足单个接口的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:43:24