Create route to webapi method with parameters via querystring

4

I have the following route in the WebApiConfig class of an AspNet WepApi project

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}"
        );

Edited: Using the @GabrielColetta response : The route is as it is below, and now works with http://localhost:62027/Pedidos/Todos?pagina=1&filtro=117 but does not work with the following url http://localhost:62027/Pedidos/Todos?filtro=117 , only works only when both parameters are passed in the querystring.

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

What works properly for the URLs and methods below:

[HttpGet]
[ResponseType(typeof(Pedido))]
public async Task<IHttpActionResult> Detalhes(int id)

http://localhost:62027/Pedidos/Detalhes/104

But for the URL and method below does not work

[HttpGet]
[ResponseType(typeof(IPagedList<Pedido>))]
public async Task<IHttpActionResult> Todos(string filtro, string pagina)

http://localhost:62027/Pedidos/Todos?filtro=s&pagina=1
http://localhost:62027/Pedidos/Todos

The following message is displayed:

I have another AspNet MVC project that has the same route and works properly, what is the reason WebAPI does not work? What is the right way?

  • WebAPI project has only one route and one route file
asked by anonymous 27.08.2017 / 21:35

2 answers

3

He is not finding because the {id} of his route is not optional, so his entire route must have a value for {id} or he will not find a route.

Set your route this way and it will work:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional }
);

For the url without the page value to work you have to put a default value for page:

[HttpGet]
[ResponseType(typeof(IPagedList<Pedido>))]
public async Task<IHttpActionResult> Todos(string filtro, string pagina = "")

Or you will have to overload the All method with only one parameter.

    
03.09.2017 / 00:40
0

You are passing the wrong parameter when calling the action. The error message is page=1 and the action is waiting for the variable named pagina .

    
27.08.2017 / 23:40