0
votes

i am new to web api and i am trying to do jquery post request but i am getting that error Message":"The requested resource does not support http method 'POST' i have tried many sulotions but nothing worked for me

there is my code

controller

 public class ProductsController : ApiController
    {
        List<Product> products = new List<Product>
        {
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        };

        [HttpGet]
        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        [HttpGet]
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        [HttpPost]
        public IHttpActionResult AddProduct([FromBody] Product p)
        {
            var product = new Product();
            if (p.Name == null || p.Price <= 0)
            {
                return NotFound();
            }
            product.Id = products.Last().Id +1;
            product.Name = p.Name;
            product.Price = p.Price;
            products.Add(product);
            return Ok(products);
        }
    }

html and js

<!DOCTYPE html>
<html>
<head>
    <title>Product App</title>
</head>
<body>

    <div>
        <h2>All Products</h2>
        <ul id="products" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product" />
    </div>
    <div>
        <h2>Add New Product</h2>
        <input type="text" id="newProd" placeholder="product name" size="7" />
        <input type="text" id="newProdPrice" placeholder="product price" size="7" />
        <input type="button" value="Add" onclick="add();" />
    </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
    var uri = 'api/products';

    //works fine
    $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
              // Add a list item for the product.
              $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
          });
    });

    function formatItem(item) {
      return item.Name + ': $' + item.Price;
    }

    //works fine
    function find() {
      var id = $('#prodId').val();
      $.getJSON(uri + '/' + id)
          .done(function (data) {
            $('#product').text(formatItem(data));
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err);
          });
    }

    function add() {
        var _name = $('#newProd').val();
        var _price = $('#newProdPrice').val();
        var p = {name:_name, price:_price};
        $.ajax({
            type: 'POST',
            url: uri,
            data: JSON.stringify(p),
            success: OnComplete,
            contentType: "application/json"
        });
    }

    function OnComplete(data) {
        $("#products").empty();
        $.each(data, function (key, item) {
            // Add a list item for the product.
            $('<li>', { text: formatItem(item) }).appendTo($('#products'));
        });
    }
    </script>
</body>
</html>

and web api

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

when i change the httppost on addProduct to httpget anxd the json request to get it works fine but when i do it with post i get that error

i have tried do that frombody and still didnt work

thanks for the helpers

1
Are you calling the right endpoint? The URL looks like it should be api/products/addproduct.Rory McCrossan
i guess i dont - how i do it?Erez
@Erez, the urivariable you setted above has a different path (var uri = 'api/products';). I'm guessing you should've appended the method name in it when calling getJSON(uri)Eric Wu
@EricWu i would like to knowhow to do that i have tried to do (var uri = api/products + AddProduct) but it didnt workErez
@Erez, I'm also not a genius in this area, but I guess you should name the controlller within the uri? Like Rory said, perhaps your uri should have the value of api/products/addproduct by the time the $.ajax is called.Eric Wu

1 Answers

4
votes

well i found an answer just had to add rout before that post method

[Route("api/products")]
[HttpPost]
public IHttpActionResult AddProduct([FromBody] Product p)
{
    var product = new Product();
    if (p.Name == null || p.Price <= 0)
    {
          return NotFound();
    }
    product.Id = products.Last().Id +1;
    product.Name = p.Name;
    product.Price = p.Price;
    products.Add(product);
    return Ok(products);
}

that fixed that of anyone have other answers please post them here