Search code examples
c#asp.netasp.net-mvcasp.net-web-apiasp.net-mvc-routing

Calling Methods from one API is done but facing Not found error on second API


I have two Wep APIs. I have done CRUD operation using one eg. Customer. But when I built another Similar Web API and called a method It shows:

{,…} Message: "No HTTP resource was found that matches the request URI http://localhost:23995/Product/Insert'."

MessageDetail: "No route providing a controller name was found to match request URI '[[same link as above here]]'"

Here is my JS Calling Method:

$scope.Insert = function () {    

    $http({
        method: 'post',
        url: 'http://localhost:23995/Product/Insert',
        data: JSON.stringify($scope.Product)
    }).then(function (response) {
        alert("chec");

    });
}

In Product Controller

// Insert 
[HttpPost]
[Route("{controller}/Insert")] 
public string Insert([FromBody] Product newProd) { 
    newProd.Insert(); 
    return newProd.DbResponse; 
} 

In supplier Controller

// Insert 
[HttpPost] 
[Route("{controller}/Insert")] 
public string Insert([FromBody] Product newProd) { 
    newProd.Insert(); 
    return newProd.DbResponse; 
}

Solution

  • Assuming you already have attribute routing enabled.

    Attribute Routing in ASP.NET Web API 2

    To enable attribute routing, call MapHttpAttributeRoutes during configuration. This extension method is defined in the System.Web.Http.HttpConfigurationExtensions class.

    using System.Web.Http;
    
    namespace WebApplication
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                // Other Web API configuration not shown.
            }
        }
    }
    

    and assuming that given the route you are getting the error on

    http://localhost:23995/Product/Insert
    

    Your product controller should look something like this.

    [RoutePrefix("product")]
    public class ProductController : ApiController {
        // ... other code removed for brevity
    
        // Insert 
        // eg: POST /product/insert
        [HttpPost]
        [Route("insert")] 
        public string Insert([FromBody] Product newProd) {...}
    }
    

    and your supplier controller would look very similar

    [RoutePrefix("supplier")]
    public class SupplierController : ApiController {
        // ... other code removed for brevity
    
        // Insert 
        // eg: POST /supplier/insert
        [HttpPost]
        [Route("insert")] 
        public string Insert([FromBody] Product newProd) {...}
    }
    

    you calling JavaScript should then be able to properly call the desired methods