Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello im having a problem setting up a route in my web api 2 project. I cannot seem to be able to create this kind of route with attribute routing

/api/{controller}/?object_id=5

It allways comes bact as 404...

If I type /api/{controller}/object?object_id=5 I get the results that I want...

Is there a way to make this happen?

Thanks, B

What I have tried:

My route looks like this
C#
[Route("{object_id}"];
Posted
Updated 30-Sep-16 4:41am

1 solution

The way web API routes work is you need to add

C#
config.MapHttpAttributeRoutes();


To your WebApiConfig.cs file if it isn't there.

Then as for the route you have two attributes to keep in mind, RoutePrefix and Route.

So an example of this would be

C#
[RoutePrefix("api/people")]
public class PeopleController : Controller
{
   [Route("names")]
   public IHttpActionResult GetNames()
   { 
      var names = //do a DB select operation or something
      return Ok(names);
   }
}


This example allows you to use the url http://localhost/api/people/names instead of the uglier version of http://localhost/people/getnames.

Now for actions with parameters in web api routes you'd do something like

C#
[RoutePrefix("api/people")]
public class PeopleController : Controller
{
   [Route("names/{personId}")]
   public IHttpActionResult GetNameForPersion(int personId)
   { 
      var names = //do a DB select operation or something
      return Ok(names);
   }
}


This would allow you add an ID that represents a person to the URL. Keep in mind, the parameter name in your action must be the same name used in the route. Otherwise i believe you'll get a 404 error.

So this url would be something like http://localhost/api/people/names/1

If you have any more questions here is a good reference:

Attribute Routing in ASP.NET Web API 2 | The ASP.NET Site[^]
 
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