9

I want to use query parameters in my endpoint attributes but I'm not sure how to use them.

I tried this:

[HttpPost("fooBar/{version}?amount={amount}&date={date}")]

But I get this error instead:

Microsoft.AspNetCore.Routing.Patterns.RoutePatternException: The literal section '?amount=' is invalid. Literal sections cannot contain the '?' character. at Microsoft.AspNetCore.Routing.Patterns.RoutePatternParser.Parse(String pattern)

Or, what's the proper approach to set the query parameters if I want to hit an endpoint that looks like the one above?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Euridice01
  • 2,510
  • 11
  • 44
  • 76

1 Answers1

14

Don't use them in the route template, they will be included once there are matching parameters in the action.

//POST fooBar/v2?amount=1234&date=2020-01-06
[HttpPost("fooBar/{version}")]
public IActionResult FooBar(string version, int amount,  DateTime date) {
    //...
}

Or explicitly state where they will come from using attributes

//POST fooBar/v2?amount=1234&date=2020-01-06
[HttpPost("fooBar/{version}")]
public IActionResult FooBar([FromRoute]string version, [FromQuery]int amount,  [FromQuery]DateTime date) {
    //...
}

Reference Model Binding in ASP.NET Core

Nkosi
  • 235,767
  • 35
  • 427
  • 472