我創建了一個 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],它也說同樣的錯誤。我為同樣的問題閱讀了這篇文章,但它說不要添加[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;
}
uj5u.com熱心網友回復:
例外訊息告訴您問題:
身體被推斷,但該方法不允許推斷身體引數
binder 已經將UserLogin引數作為引數從 body 中推斷出來,但推斷的 body 引數是不允許的。
最簡單的方法是向引數添加[FromBody]屬性UserLogin,但是,在這種情況下,您應該真正將方法更改為 POST,因為 GET 請求沒有正文。
app.MapPost("/userLogin", (IUserRepository ur, [FromBody]UserLogin userLogin) => {...}
不幸的是,不可能使用[FromQuery]最小 API 中的屬性從查詢字串值系結復雜物件,因此 IMO 的最佳選擇是使用[FromBody]和MapPost.
如果您需要使用MapGet,可以通過向您的類添加靜態BindAsync方法來解決UserLogin- 更多詳細資訊可以在此博客文章中找到。另一種選擇是傳遞HttpContext給操作并從背景關系中獲取值 - 請參閱系結 [FromForm] 的類似答案- 您將使用ctx.Request.Query["username"]從 HttpContext 獲取用戶名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449827.html
標籤:asp.net 核心 http asp.net-core-webapi .net-6.0 最小的 API
