消息:请求的资源不支持http方法'POST'

时间:2016-01-27 13:23:33

标签: jquery asp.net json ajax asp.net-web-api

我是web api的新手,我正在尝试做jquery post请求 但我得到了那个错误 消息“:”请求的资源不支持http方法'POST'  我尝试了许多闷热但没有任何作用对我来说

有我的代码

控制器

 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和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>

和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 }
            );
        }

当我将addProduct上的httppost更改为httpget时,json请求使其正常工作 但是当我用帖子做的时候我得到了那个错误

我已经尝试过这样做 仍然没有工作

感谢帮助者

1 个答案:

答案 0 :(得分:4)

我发现答案只需要在帖子方法之前添加溃败

[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);
}

修正了那个问题 任何人都有其他答案,请在这里发布