Why do I have a 404 error when I try to publish data in a WebAPI action?

advertisements

Why I got an 404 error when I try to post data to a WebAPI action?

C#:

public class ProductsController : ApiController
{
    [HttpPost]
    public List<Product> GetProductsByCategoryId(int categoryId, string title)
    {
        return new List<Product>
        {
            new Product { Id = 1 , Name = "Test" }
        };
    }
}

jQuery:

$.ajax({
    url: '/api/products',
    type: 'POST',
    data: {
        categoryId: 12,
        title: 'ABC'
    },
})


By default, Web API tries to match simple parameters from the URI, but you are supplying them in the body. In my original answer, I forgot you can't use FromBodyAttribute more than once. In this case, I'd create a model class to contain the values. Web API will then read this "complex" type from the body.

public class ProductCategoryModel
{
   public int CategoryId { get; set; }
   public string Title { get; set; }
}

public class ProductsController : ApiController
{
    [HttpPost]
    public List<Product> GetProductsByCategoryId(ProductCategoryModel model)
    {
        return new List<Product>
        {
            new Product { Id = 1 , Name = "Test" }
        };
    }
}