MinimalAPI - 您是要将 "Body (Inferred)" 参数注册为服务还是应用 [FromService] 或 [FromBody] 属性?

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

我创建了一个 asp.net 核心空项目,每当我尝试 运行 我的应用程序时,它都会给我如下所示的错误。我一点击播放就无法到达终点,它给出了错误。

System.InvalidOperationException HResult=0x80131509 Message=Body 已被推断,但该方法不允许推断正文参数。 以下是我们找到的参数列表:

Parameter           | Source                        
---------------------------------------------------------------------------------
ur                  | Service (Attribute)
userLogin           | Body (Inferred)


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

不知道为什么会出现此错误。然后我尝试添加 [FromService] 并且它也说同样的错误。我读了这个 article 来解决同样的问题,但它说不要添加 [Bind] ,我一开始就没有添加 [Bind] 而是使用 [FromService] 但我仍然得到同样的错误。我做错了什么吗?

Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ApplicationDbContext>(x =>
    x.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

builder.Services.AddScoped<IUserRepository, UserRepository>();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapGet("/userLogin", (IUserRepository ur, UserLogin userLogin) =>
{
    return ur.Get(userLogin);
});

if (app.Environment.IsDevelopment())
{
    app.UseSwagger(x => x.SerializeAsV2 = true);
    app.UseSwaggerUI();
}

app.Run();

UserLogin:

 [Keyless]
public class UserLogin
{
    public string Username { get; set; }
    public string Password { get; set; }
}

UserRepository:

public User Get(UserLogin userLogin)
        {   // get the username and password make sure what was entered matches in the DB then return the user
            var username =_dbContext.Users.Find(userLogin.Username, StringComparison.OrdinalIgnoreCase);

            return username;
        }

异常消息告诉您问题所在:

Body was inferred but the method does not allow inferred body parameters

活页夹已将UserLogin参数推断为body的参数,但不允许推断body参数。

实现此功能的最简单方法是将 [FromBody] 属性添加到 UserLogin 参数,但是,在这种情况下,您应该真正将方法更改为 POST,因为 GET 请求没有 body.

app.MapPost("/userLogin", (IUserRepository ur, [FromBody]UserLogin userLogin) => {...}

不幸的是,无法在最小 API 中使用 [FromQuery] 属性从查询字符串值绑定复杂的 objects,因此 IMO 的最佳选择是使用 [FromBody]MapPost.

如果您需要使用 MapGet,可以通过向 UserLogin class 添加静态 BindAsync 方法来获得 work-around - 更多详细信息可以在 this blog post. Another alternative is to pass HttpContext to the action and take the values from the context - see this similar answer for binding [FromForm] 中找到 - 您将使用 ctx.Request.Query["username"] 从 HttpContext 中获取用户名。