Search code examples
c#asp.net-web-apiasp.net-web-api-routing

Getting error while calling WebApi


I am trying to create an API and trying to access it via chrome, expecting it to return the list of Items

public class ProductController : ApiController
{
    Product product = new Product();
    List<Product> productList = new List<Product>();

    [HttpGet]
    public HttpResponseMessage GetTheProduct(int id)
    {
        this.productList.Add(new Product {Id = 111,Name= "sandeep" });
        return Request.CreateResponse(HttpStatusCode.OK, this.productList.FirstOrDefault(p => p.Id == 111));
    }
}

I have not added route so wanna run it using default route but when i am running it, am getting

No HTTP resource was found that matches the request URI 'http://localhost:65098/api/GetTheProduct()'. No type was found that matches the controller named 'GetTheProduct()'.

Suggest me what all things are required to make it work.


Solution

  • If using default routes then configuration may look like this

    public static class WebApiConfig {
        public static void Register(HttpConfiguration config) {
    
            // Convention-based routing.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    

    This would mean that routing is using convention-based routing with the following route template "api/{controller}/{id}"

    Your controller in its current state is not following the convention. This results in requests not being matched in the route tables which result in the Not Found issues being experienced.

    Refactor the controller to follow the convention

    public class ProductsController : ApiController {
        List<Product> productList = new List<Product>();
    
        public ProductsController() {
            this.productList.Add(new Product { Id = 111, Name = "sandeep 1" });
            this.productList.Add(new Product { Id = 112, Name = "sandeep 2" });
            this.productList.Add(new Product { Id = 113, Name = "sandeep 3" });
        }
    
        //Matched GET api/products
        [HttpGet]
        public IHttpActionResult Get() {
            return Ok(productList);
        }
    
        //Matched GET api/products/111
        [HttpGet]
        public IHttpActionResult Get(int id) {
            var product = productList.FirstOrDefault(p => p.Id == id));
            if(product == null)
                return NotFound();
            return Ok(product); 
        }
    }
    

    Finally based on the route template configured then the controller expects a request that looks like

    http://localhost:65098/api/products/111.
    

    To get a single product that matches the provided id if it exists.

    Reference Routing in ASP.NET Web API