Home > Net >  How to apply optional parameter in the middle of a route in c#?
How to apply optional parameter in the middle of a route in c#?

Time:08-08

I have a controller as

[ApiController]
[Route("api/getData/")]

and the GET method with route

[HttpGet("{name}/{message}/{num}")]
{ 
     public async GetAsync(string name, string message,int num) {some code}
}

Now I also want to send 'message' as optional without changing the route and set it to default value of empty string in the method. So I am using both these functions now, independently they both work fine but not together.

[HttpGet("{name}/{num}/{message?}")]
{ 
    public async GetAsyncOptional(string name, int num , string message="") {some code}
}

But I keep getting the error in StartUp.cs in

app.UseEndpoints(endpoint => {endpoint.MapController();

    System.ArgumentException:'An optional parameter cannot have default value.(Parameter 'route template')

CodePudding user response:

your two routes are overlapped, you have to give action name to separate them

[HttpGet("/~api/getDataOptional/{name}/{num}/{message?}")]
public async Task<ActionReslt> GetAsyncOptional(string name, int num , string message="") 
{
...
     
}

or I don't see why dont' use one route for two, only if a query string parameters order is very important for you.

CodePudding user response:

I can advise you to make class for request like, because you approach in answer seems like bad:

1)

class RequestData 
{
   string Name {get;set;}
   int Age {get;set;}
   string Message {get;set;}
}
  1. Then make your controller:

    [ApiController] [Route("api/data")] public class DataController {}

And method is: 3)

[HttpGet]
public async Task<ActionResult> GetAsyncOptional([FromBody] RequestData data) 
{
   // 
}

That's more complex because if you extend your format for 4 and 5 argument, you will change your route one more time, It is not necessary. Optional params can be in request body.

  • Related