Reputation: 9080
I added a method in my web api controller:
public String GetpeopleInFamily(string familyId)
I followed some examples from this question: Custom method names in ASP.NET Web API
I updated my RouteConfig.cs file based off of what I read above: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
routes.MapHttpRoute("DefaultApiWithActionAndId", "Api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint("Get") });
routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint("Post") });
}
But I'm still getting a 404 when calling the method:
Request GET /api/people/GetpeopleInFamily/101 HTTP/1.1
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:17438/api/people/GetpeopleInFamily/101 '.","MessageDetail":"No action was found on the controller 'people' that matches the request."}
What do I need to do to get this to work? As well as, is this best practice to add custom methods that return a more complicated data set?
Upvotes: 0
Views: 3003
Reputation: 3313
The familyId
is not mapped in the route. So you can create a new Mapping wich adds familyId to the id mapping or rewrite the parameter of GetPeopleInFamily
to id
.
Rewrite:
public string GetPeopleInFamily(string id)
Create new route: When you create a new route be sure that you remove the mapping with the id
otherwise it won't work.
routes.MapHttpRoute("DefaultApiWithActionAndFamilyId", "Api/{controller}/{action}/{familyId}", new { familyId = RouteParameter.Optional }, new { familyId = @"\d+" });
Upvotes: 1
Reputation: 3182
you need to configure your web API route to accept a familyId parameter.
config.Routes.MapHttpRoute(name: "newont",
routeTemplate: "api/{controller}/{familyId}/{id}",
defaults: new { controller = "Controllername", familyId= "familyId", new { id = RouteParameter.Optional }}
);
Upvotes: 1