Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a parameter in minimal API as an optional in .NET Core

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?

like image 972
Ehsan Akbar Avatar asked Nov 30 '25 19:11

Ehsan Akbar


1 Answers

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";
});
like image 90
Tiny Wang Avatar answered Dec 04 '25 20:12

Tiny Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!