How do I add parameters and the DbContext to a minimal API call?

Falanga, Rod, DOH 260 Reputation points
2024-11-25T20:54:02.5533333+00:00

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?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,684 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 68,306 Reputation points
    2024-11-25T21:08:32.9766667+00:00

    This pretty covered in the docs

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/parameter-binding?view=aspnetcore-9.0

    As it’s a GET method the proper attribute is [FromQuery] for query string values and [FromService] for injection.

    1 person found this answer helpful.

  2. Alex1aq 0 Reputation points
    2024-11-26T05:33:44.75+00:00

    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

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.