user20358
user20358

Reputation: 14766

getting routes right with asp.net webapi 2

I am trying to get my routes to work but end up getting an error.

This is currently my only route:

    config.Routes.MapHttpRoute(
          name: "ActionApi",
          routeTemplate: "api/{controller}/{action}/{id}",
          defaults: new { id = RouteParameter.Optional }
      );

I commented this one out as I thought it was the problem

   //config.Routes.MapHttpRoute(
    //    name: "DefaultApi",
    //    routeTemplate: "api/{controller}/{id}",
    //    defaults: new { id = RouteParameter.Optional }
    //);

These are the two methods I have :

    public class ProductsController : ApiController
    {
      Product[] products = new Product[] 
      { 
        new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
      };

    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }

    [ActionName("GetAllProducts")]
    public IEnumerable<Product> GetAllProductsAction()
    {
        return products;
    }
  }

When trying to access it on this URL: http://localhost:27720/api/products/GetAllProducts I get an error: Multiple actions were found that match the request

How can that be? I have named one of them with a specific action method. Is this by design or did I configure my routes wrongly?

Upvotes: 1

Views: 85

Answers (1)

Jeremy Cook
Jeremy Cook

Reputation: 22153

public IEnumerable<Product> GetAllProducts() and public IEnumerable<Product> GetAllProductsAction() with the ActionName("GetAllProducts") attribute definitely resolve to the same URL, hence the Multiple actions were found that match the request error.

Change the action name of the one or the method name of the other...or remove one of the methods because they are currently redundant.

Upvotes: 1

Related Questions