5
I have the following route in class WebApiConfig
of a project Aspnet Wepapi
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}"
);
Edited: Using @Gabrielcoletta’s reply: The Route was the way it is below, and now the url works http://localhost:62027/Pedidos/Todos?pagina=1&filtro=117
but does not work the following url http://localhost:62027/Pedidos/Todos?filtro=117
, only works when both parameters are passed in querystring.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
What works properly for the URL 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
Being displayed the following message:
I have another project Aspnet MVC which has the same route and works properly, why does the Webapi not work? which is the correct way?
- Webapi project has only one route and a single route file
I edited my question the result of your answer
– Ricardo
@Ricardo answered your edition.
– Gabriel Coletta
Because the route works without standard parameters in the MVC project but not in the WEBAPI?
– Ricardo
Does it work? I believe you’re using an older version of the framework or made some configuration that doesn’t remind you to say it’s optional. If you really can, standard MVC and the Webapi are two totally different Assembly and there will be cases where some divergences occur, even if the syntax is similar.
– Gabriel Coletta
Just complementing, but I always use all optional parameters, except in cases where explicitly one of them I have to have. Moreover, in MVC it works because the MVC Binding system is different from the WEBAPI. In MVC it does everything automatically, and when it has no value, Binding puts a default value. In the API it is different as Binding understands that all parameters are mandatory.
– Grupo CDS Informática
edtei to
Todos(string filtro = "", string pagina = "")
and it worked– Ricardo
Yes, when you put default values like I commented, it will understand that you do not need to pass that parameter in the url.
– Gabriel Coletta
@Ricardo, if possible, marks Gabriel’s post as a response.
– Grupo CDS Informática