This pretty covered in the docs
As it’s a GET method the proper attribute is [FromQuery] for query string values and [FromService] for injection.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am working on a Blazor app, which has two projects. One of the Blazor UI and the other is a minimal API project. I've got some endpoints working fine, but now I've got a conundrum. I want to be able to pass a parameter, in this case a Boolen value, plus the DbContext like I've been doing in the other endpoints, in the minimal API. I found a Microsoft Learn course, which works if no minimal API is involved. It's here. This is for .NET 8 (which I've got to use for now). Here's my code in the minimal API:
app.MapGet("/tasks", async ([AsParameters] bool ActiveStatus, TimetrackTestContext context) =>
{
Response<KeyVaultSecret> kvVal = await GetConnectionString();
context.Database.SetConnectionString(kvVal.Value.Value);
var tasks = await context.RTasks.OrderBy(tasks => tasks.Desc).ToListAsync();
return Results.Ok(tasks);
})
.WithName("GetTasks")
.WithOpenApi();
But this has the problem in that the AsParameters attribute is more appropriate for a Blazor UI, rather than using it in a minimal API. However, when I run it in the debugger, its close, but not complete. For example, the ActiveStatus has a value of False, but I'm sure it is always False.
How do I make this work in a minimal API project?
This pretty covered in the docs
As it’s a GET method the proper attribute is [FromQuery] for query string values and [FromService] for injection.
To add parameters and DbContext
to a minimal API call in ASP.NET Core, inject the DbContext
into the endpoint by including it as a parameter. For example:
app.MapGet("/items/{id}", async (int id, YourDbContext db) => await db.Items.FindAsync(id));
Here, id
is a route parameter, and YourDbContext
is injected for database access. Ensure YourDbContext
is registered in the IServiceCollection
in Program.cs
using builder.Services.AddDbContext<YourDbContext>()
.
Source: Rutificador