Click here to Skip to main content
15,901,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
Posted
Updated 10-Oct-17 17:27pm
v2
Comments
j snooze 6-Sep-17 17:30pm    
does it work if you turn off authorization and just type the api url in your browser of choice with a productid? What if you strip it all the way down to a simple get by commenting all the other stuff including authorization checks. I recently had the joy of playing with .NET core webapi + angular2 for the first time, only to realize the default route on the project didn't have the action as part of it it was only assuming api/[controller]

404 is "page not found". You are looking for a route that does not exist. As "j snooze" mentions, as part of the debugging of routes, try it manually. Also, use the Web Browser debugging tools and check the actual raw conversation to see if the URLs being called are in fact what your route table is expecting.

Additionally, here is a full list of HTTP Status Codes[^]
 
Share this answer
 
Did you check the Cross-Origin Requests (CORS) setting? I'm guessing, this is the error the application is throwing when invoking the API through jQuery AJAX request.

HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). XHR OPTIONS

Check out this article, there is a section explaining the CORS setting and you can download the code and do some experiment with it.
ASP.NET MVC Tooltip using Web API, Bootstrap Popover and jQuery UI dialog[^]
 
Share this answer
 
$.ajax({
                        url: "/api/cart",
                        type : "Post",
                        data: $(this).next().val()
});
 
window.location.href = "~/Login/Account";
 
Backend code
private ApplicationDbContext _context = new ApplicationDbContext();
 
private IEnumerable<IndividualTable> GetContext
{
    get {return _context.IndividualTable ;}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900