I am looking for tips on how to set up routing in a Web API project. I have set up a controller called Resident with a method as follows:
public ResidentModel GetResidentInfo(int resId)
{
//code to return ResidentModel object
}
I have tried the following to map to this method in the route.config file.
routes.MapRoute(
name: "Resident",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
I am trying to access this method through a variety of ways:
http://localhost/resident/1 or
http://localhost/resident/GetResidentInfo/1 etc...
I’m looking for some guidance on the process of setting up a controller then mapping to that controller method as when I try to access methods I’ve created it does not recognize them. Thanks in advance.
First, your controller class should be called
ResidentController(not justResident) and inherit fromApiController(it really needs to implementIHttpController, but inheriting from that class is the easiest way).Second, you should use
MapHttpRouteinstead ofMapRoutefor Web API controllers.Next, the paramter
idon the route doesn’t match the parameter in your action. If you have a route such as the one below, you should be able to get to the second URL:And this would match the first one: