我创建了一个空的 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?
不清楚为什么会出现这个错误。我尝试添加 [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();
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;
}