2

I'm trying to create a simple WebAPI in ASP.NET. I put it in IIS. When I try to browse the site it's all good:

enter image description here

But when I try to get a result from the API, I get this error:

enter image description here

Controller:

public class ProductController : 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;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }

WebApiConfig:

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Golan Kiviti
  • 3,895
  • 7
  • 38
  • 63

1 Answers1

2

You host it on the application accessed by /api, so you need an additional /api to match the routing:

http://localhost:6060/api/api/Product

If you don't want that, then either give the api site a more sensible name, remove the api/ from the route, or both.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • That's because your controller is called `ProductController`, singular, so you need Product, not Products. – CodeCaster May 17 '16 at 11:53
  • Yeah so what did your research show up? Is the config you show the entire config, or did you cut some lines from it? Did you [register WebAPI](http://stackoverflow.com/questions/20621825/asp-net-mvc-webapi-404-error) and [install the WebHost package](http://stackoverflow.com/questions/25450105/globalconfiguration-does-not-contain-a-definition-for-configure)? – CodeCaster May 17 '16 at 11:57
  • its the entire config and i didn't do anything of the above – Golan Kiviti May 17 '16 at 12:01
  • 2
    Do you now want me to tell you that you should? :) – CodeCaster May 17 '16 at 12:02
  • I just followed the following guide: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api, and it seems to worked for him and there wasnt any reference to what you mentioned – Golan Kiviti May 17 '16 at 12:21
  • 1
    @Pachu so you got it figured out now? What did solve the issue eventually? – CodeCaster May 17 '16 at 12:46