I am creating a ASP.NET MVC web site and as the title say i am trying to send a POST request to Web Api controller with jquery, but am always receiving a 404 error. The crazy thing is that in the .NET framework 4.5 the exact the same thing worked, but in the .NET framework 4.6.2 it really doesn't. I 've found a lot of threads in google explaining what it might go wrong, but none of these worked. So, here is my code now:
The Web Api Class:
[Authorize]
public class CartController : ApiController
{
private ApplicationDbContext _context;
public CartController()
{
_context = new ApplicationDbContext();
}
[HttpPost]
public IHttpActionResult AddToCart(string productId)
{
if (!ModelState.IsValid || !ItemIsValid(productId))
return BadRequest();
var newCartItem = new ShoppingCartItem
{
ProductId = productId,
UserId = User.Identity.GetUserId()
};
_context.ShoppingCartItems.Add(newCartItem);
_context.SaveChanges();
return Ok();
}
private bool ItemIsValid(string productId)
{
return Enumerable.Any(_context.Products, contextproduct => contextproduct.Id.ToString() == productId && contextproduct.NumberAvailable > 0);
}
}
My jQuery code:
$(".buy-button").click(function() {
if (@User.Identity.IsAuthenticated.ToString().ToLower() === true) {
$.ajax({
url: "/api/cart",
method: "POST",
data: $(this).next().val()
}).done(function() {
alert("Product succesfully added to cart!");
});
} else {
window.location.href = "@Url.Action("Login", "Account")";
}
});
The Global.asax code:
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
It would be great if someone could help me. I have spent over 6 hours on this bug, and i can't still find out what i am doing wrong.
What I have tried:
1) Some threads said that the order of the "calls" in the Global.asax matters, so i changed the position of '
RouteConfig.RegisterRoutes(RouteTable.Routes);
'
in every possible place.
2) Added Route Attributes in my Web Api action([Route("api/Cart/AddToCart")]) which i know from experience that is redundant ... and changed my jQuery code accordingly.
3) Instead of adding attributes, i added to Routes directly to the Web Api Config.
4) I also tried to call the Api with postman directly(i removed the Authorize attribute of course).
None of these worked.