0

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.

4
  • Silly question: Is your controller called Resident or ResidentController? Can you try changing the redId parameter to id. and use that second URL? Commented Nov 28, 2012 at 0:42
  • What happens if you drop the "/1" in the request, and set "1" as the default parameter in the method? Commented Nov 28, 2012 at 0:44
  • 1
    Actually for a Web API project you probably need a URL like http://localhost/api/resident/GetResidentInfo/1 Commented Nov 28, 2012 at 0:45
  • Also, how does your controller action return? What does that line look like? Commented Nov 28, 2012 at 0:45

1 Answer 1

4

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" });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response the control is called ResidentController I figured you guys would take that as a given my apologies. Thank you Carlos this solved my issue I was able to get response at the following url after following your routing. localhost/api/resident/GetResidentInformation/?resId=1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.