Lijin John Lijin John - 3 months ago 23
C# Question

Not able to call webApi from controller using jQuery Ajax

There are many questions related to webApi not getting called but i tried every solution and i am not able to get the right solution for my problem.
i have a webApi like this

public class shoppingCart : ApiController
{
[HttpPost]
public string getDetails()
{
return "HttpPost";
}
[HttpGet]
public string getDetails1()
{
return "HttpGet";
}
[HttpPut]
public string getDetails2()
{
return "HttpPut";

}
[HttpDelete]
public string getDetails3()
{
return "HttpDelete";
}
}


my global.asax.cs file is like this

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}


my WebApiConfig.cs file is like this

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


my routeConfig.cs file is like this

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}


my jQuery Ajax script is like this

$('#btnAjax').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/api/shoppingCart/getDetails',
success: function (returnData) {
alert('success');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error');
}
});
});


whenever i try to call the web api i get an error

enter image description here

please somebody help me to fix the issue.
Thank you

Answer

Try renaming your controller to shoppingCartController. As far as I know ASP.NET will look at the request and then search for a controller with the name request + Controller. I always try to be on the safe side by adding Controller.