Home > Blockchain >  Make a parameter in minimal api as an optional in .NET Core
Make a parameter in minimal api as an optional in .NET Core

Time:07-08

I have this API as you can see:

app.MapGet("/api/fund/{fundCode}", ([FromServices] IMediator mediator,string fundCode)
    => mediator.Send(new GetFundsQuery(fundCode)));

I want to set fundcode as an optional parameter to my API, so I changed it to

app.MapGet("/api/fund/{fundCode?}", ([FromServices] IMediator mediator,string fundCode)
    => mediator.Send(new GetFundsQuery(fundCode)));

But it didn't work, and when I call this address

https://localhost:7147/api/fund

I get an http 404 error. Why?

CodePudding user response:

When I used code below, I'll get "null" as a response when I call localhost:port/hello. But when I use string id as the parameter, I got 400 bad request...

app.MapGet("/hello/{id?}", (string? id) =>
{
    if (id == null)
    {
        return "null";
    }
    else {
        return id;
    }

});

I also tried to use code below and when I call localhost:port/hello, I get "empty" as the response.

app.MapGet("/hello/{id?}", (string? id) =>
{
    if (id == null)
    {
        return "null";
    }
    else {
        return id;
    }

});

app.MapGet("/hello", () =>
{
     return "empty";
});

CodePudding user response:

You can try the query parameter. For example:

app.MapGet("/api/fund", GetFundsAsync).Produces<IList<Fund>>();

private async Task<IList> GetFundsAsync(IMediator mediator,string fundCode = null)
{
    return await mediator.Send(new GetFundsQuery(fundCode));
}

This way https://localhost:7147/api/fund will return results And https://localhost:7147/api/fund?fundCode=ABC will work too

  • Related