Search code examples
c#asp.net-corequery-stringmediatrasp.net-core-routing

How do I use query parameters in attributes?


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?


Solution

  • 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