Click here to Skip to main content
15,888,008 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
now in the URL i type:
localhost/api/controller/1/34.5/31.2/


but this is what i want

localhost/api/controller?Id=1&num1=34.5&num2=31.2


What I have tried:

Right now this is my Route
<pre>
[HttpGet]
[Route("api/Controller/{Id}/{num1}/{num2}/", Name = "GetInfo")]
Posted
Updated 21-Apr-20 3:55am
v2
Comments
Maciej Los 17-Apr-20 6:10am    
Please, read this: Parameter Binding in Web API[^]
Member 14800672 17-Apr-20 8:35am    
Hi,

yes i read it but it doesn't specify anything

Here's the URL i tried: https://localhost:****/api/Customer?Id=1&num1=1&num2=1.2/
but i'm getting this error
No HTTP resource was found that matches the request URI

However it works if i use slashes: https://localhost:****/api/Customer/Id/1/num1/1.1/num2/3.2/


Here's the route for my method:
[HttpGet]
[Route("api/Customer/{Id}/{num1}/{num2}/", Name = "GetCustomers")]
public IHttpActionResult GetCustomers(int Id, double num1, double num2)
{
}

And here's my register method:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{Id}/{num1}/{num2}",
defaults: new {
Id = RouteParameter.Optional,
num1= RouteParameter.Optional,
num2= RouteParameter.Optional
}
);

}

1 solution

Attribute Routing in ASP.NET Web API 2 | Microsoft Docs[^]

You have a single route on your action which requires all three parameters to be passed within the URL. When you put the parameters in the querystring, that route no longer matches.

If you want to pass the values in the querystring instead, change your route to:
C#
[HttpGet]
[Route("api/Customer", Name = "GetCustomers")]
public IHttpActionResult GetCustomers(int Id, double num1, double num2)
If you want to support both options, you can have multiple routes on the same action, although they obviously can't have the same name:
C#
[HttpGet]
[Route("api/Customer")]
[Route("api/Customer/{Id}/{num1}/{num2}/", Name = "GetCustomers")]
public IHttpActionResult GetCustomers(int Id, double num1, double num2)
NB: If all of the actions in your controller have the same route prefix, you might want to use the RoutePrefix attribute[^] on your controller instead.
C#
[RoutePrefix("api/Customer")]
public class CustomerApiController : ApiController
{
    [HttpGet]
    [Route("")]
    [Route("{Id}/{num1}/{num2}/", Name = "GetCustomers")]
    public IHttpActionResult GetCustomers(int Id, double num1, double num2)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900