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

ASP.NET Core Web API报错:Body被推断但方法不允许该参数

ASP.NET Core MapGet接口依赖注入报错:Body参数推断异常

问题重现

仿写官方ASP.NET Core教程接口时,MapGet接口注入UserDB触发以下错误:

An unhandled exception occurred while processing the request.
InvalidOperationException: Body was inferred but the method does not allow inferred body parameters.
Below is the list of parameters that we found:

Parameter | Source
---------------------------------------------------------------------------------
db1 | Body (Inferred)


Did you mean to register the "Body (Inferred)" parameter(s) as a Service or apply the [FromServices] or [FromBody] attribute?

自身核心代码:

app.MapGet("/users/all", async (UserDB db1) =>
    await db1.Users.ToListAsync());

官方教程可正常运行的核心代码:

app.MapGet("/todoitems", async (TodoDb db) => 
    await db.Todos.ToListAsync());

注:将接口改为MapPost可运行,但不符合获取数据的语义。

差异分析

问题根源在于**UserDB未被正确注册到ASP.NET Core的服务容器中**:

  • 官方教程里的TodoDb已通过AddDbContext<TodoDb>(或类似方法)注册为服务,框架能自动识别它是依赖服务,会从容器中获取实例,不会当成Body参数。
  • 你的UserDB没有完成服务注册,框架无法识别它的来源,在Get请求(默认不支持Body参数)的场景下,错误地将其推断为Body参数,从而触发异常。

解决办法

有两种可行方案:

方案1:显式指定参数来源(快速临时修复)

给UserDB参数添加[FromServices]特性,强制框架从服务容器中获取实例:

app.MapGet("/users/all", async ([FromServices] UserDB db1) =>
    await db1.Users.ToListAsync());

方案2:正确注册UserDB到服务容器(规范做法)

在Program.cs中添加UserDB的服务注册代码,以EF Core DbContext为例:

builder.Services.AddDbContext<UserDB>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("UserDBConnection")));

注册完成后,原接口代码无需修改即可正常运行,框架会自动注入UserDB实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:40:46