0

I have a an ASP.NET Web API project where I have a single method in my controller as such ..

public IHttpActionResult MyMethod(int param1, int param2, int param3)
{
  var theSum = param1 + param2 + param3;
  return Ok(theSum);
}

I have the following route in RouteConfig.cs

routes.MapRoute(
  name: "MyRoute",
  url: "api/{controller}/{action}/{param1}/{param2}/{param3}",
  defaults: new { controller = "MyController", action = "MyRoute", param1 = UrlParameter.Optional, param2 = UrlParameter.Optional, param3 = UrlParameter.Optional }
  );

When I call the API with the following URL everything works as expected ..

http://localhost/api/mycontroller/mymethod?param1=2&param2=4&param3=6

Yet when I try to call the API as follows I get a 404 - The resource cannot be found error.

http://localhost/api/mycontroller/mymethod/2/4/6/

any idea why? I thought I had the route setup properly and since the parameters are .NET primitives I though I could pass them as param1/param2/param3

3
  • try nuking the trailing /? Commented Dec 14, 2015 at 20:57
  • Just tried removing the trailing / and still got the 404 Commented Dec 14, 2015 at 20:59
  • Your Action = "MyRoute" I believe should be Action = "MyMethod" Commented Dec 14, 2015 at 22:09

1 Answer 1

2

Are you using MVC5? If so I'd suggest using the Route() attribute instead the routes collection, for me at least it is easier to manage. I was able to get this working with your sample using that approach.

[Route("api/values/MyMethod/{param1}/{param2}/{param3}")]
[HttpGet]
public IHttpActionResult MyMethod(int param1, int param2, int param3)
{
    var theSum = param1 + param2 + param3;
    return Ok(theSum);
}

And then calling it via http://localhost/api/values/mymethod/2/4/6 properly returned 12.

Sign up to request clarification or add additional context in comments.

5 Comments

By using the Route attribute would I remove the entry for "MyRoute" in the RouteConfig.cs?
Yeah, remove that and just decorate the methods with your attribute
That worked! Thanks a bunch! Interesting why the route configuration in Route.Config did not work.
I think that has to do with there being 2 route configs - one for MVC style and one for WebAPI, I think you were pushing your config into the MVC route collections (RouteConfig.cs) instead of the WebApiConfig.cs
If you add something like config.Routes.MapHttpRoute( name: "MyRoute", routeTemplate: "api/values/mymethod/{param1}/{param2}/{param3}", defaults: new { controller = "Values", action = "MyMethod" } ); to the WebApiConfig and let your controller know to expect a GET [HttpGet] attribute then it should also work

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.