MinimalAPI - 您是否打算将“Body(推断)”参数注册为服务或应用 [FromService] 或 [FromBody] 属性?

Mar*_*kCo 22 http asp.net-core asp.net-core-webapi .net-6.0 minimal-apis

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

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

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?
Run Code Online (Sandbox Code Playgroud)

不知道为什么我会收到此错误。然后我尝试添加[FromService],它也显示相同的错误。我针对同一问题阅读了这篇文章,但它说不要添加[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();
Run Code Online (Sandbox Code Playgroud)

UserLogin:

 [Keyless]
public class UserLogin
{
    public string Username { get; set; }
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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;
        }
Run Code Online (Sandbox Code Playgroud)

Zac*_*lez 19

就我而言,我忘记将以下内容添加到 app.Run(); 上方的 program.cs 文件中

builder.Services.AddScoped<IUserRepository, UserRepository>();
Run Code Online (Sandbox Code Playgroud)


hal*_*ldo 14

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

推断了主体,但该方法不允许推断主体参数

绑定器已将UserLogin参数推断为来自主体的参数,但不允许推断主体参数。

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

app.MapPost("/userLogin", (IUserRepository ur, [FromBody]UserLogin userLogin) => {...}
Run Code Online (Sandbox Code Playgroud)

不幸的是,不可能使用[FromQuery]最小 API 中的属性从查询字符串值绑定复杂对象,因此我认为最好的选择是使用[FromBody]MapPost

如果您需要使用,可以通过向您的类MapGet添加静态方法来解决 - 更多详细信息可以在这篇博客文章中找到。另一种选择是传递给操作并从上下文中获取值 - 请参阅绑定 [FromForm] 的类似答案- 您可以用来从 HttpContext 获取用户名。BindAsyncUserLoginHttpContextctx.Request.Query["username"]

  • 谢谢您,我在阅读您的解释后意识到我应该将其更改为 POST 方法而不是 GET。 (2认同)