0

I have ASP.NET MVC project. I need to add WebAPI to it.

I try to add model and controller like in this tutorial (https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api)

I added model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

Here is my controller

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SmartSolutions.Models;

namespace SmartSolutions.Controllers
{
    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;
        }
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }
}

Here is WebApiConfig

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

When I launch app I have this

enter image description here

Where is my mistake may be?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325

1 Answers1

0

if the id is optional you must pass the int as nullable in the method in API controller and the URL should be api/products/GetProduct also in addition visit link you might be doing any of the error mentioned in the already asked question Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id} it has answer like to Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

 public IHttpActionResult GetProduct(int? id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
Community
  • 1
  • 1
Anil Panwar
  • 2,592
  • 1
  • 11
  • 24