Search code examples
c#routesasp.net-web-api2attributerouting

How to map query parameters with dashes in their names


Is there a way to map the query string parameter my-param to the controller method parameter myParam in Web API 2 (preferably using attribute routing)?

This means a URI like...

library.com/books?search-text=REST

...should be routed to the controller method

[HttpGet, Route("books/{search-text?}")]
public IEnumerable<Book> Get(string searchText = "") { ... }

Is this possible? The Microsoft documentation does not provide an example for that case. But it also doesn't provide some kind of grammar for route parameters, hence I'm not sure if it's exhaustive.


Solution

  • You can use the [FromUri] attribute as follows:

    [FromUri(Name = "search-text")]

    You weren't far off with your comment. If you need this as a convention you can likely create your own parameter binding in Web API:

    http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api