vikingben
vikingben

Reputation: 1652

MVC 4 Web Api Routing

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.

Upvotes: 0

Views: 988

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87218

First, your controller class should be called ResidentController (not just Resident) and inherit from ApiController (it really needs to implement IHttpController, but inheriting from that class is the easiest way).

Second, you should use MapHttpRoute instead of MapRoute for Web API controllers.

Next, the paramter id on 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:

routes.MapHttpRoute(
    name: "WithAction",
    routeTemplate: "{controller}/{action}/{resId}");

And this would match the first one:

routes.MapHttpRoute(
    name: "DefaultAction",
    routeTemplate: "{controller}/{resId}",
    defaults: new { action = "GetResidentInfo" });

Upvotes: 4

Related Questions