【问题标题】:JSON data not being saved in WebAPIJSON数据未保存在WebAPI中
【发布时间】:2018-03-08 03:10:29
【问题描述】:

我正在一起学习关于 AngularJS 和 WebAPI 的 Pluralsight 课程。我正在尝试使用PUT 保存从客户端发送到服务器的数据,但数据没有保存,我没有收到任何错误。此外,它不会触发正确的服务器端代码,因为没有捕获断点。我试图改变HTTP 方法的类型,但我需要这个。唯一被发回的是来自服务器的"204: No Content" 代码。

这就是PUTPOST 方法的样子。这些方法中的任何一个断点都不会被捕获。

// POST: api/Products
public void Post([FromBody]Product product) // Creating a product
{
    var productRepository = new ProductRepository();
    var newProduct = productRepository.Save(product);
}
// PUT: api/Products/5
public void Put(int id, [FromBody]Product product) // Updating a product
{
    var productRepository = new ProductRepository();
    var updatedProduct = productRepository.Save(id, product);
}

ProductRepository 看起来像这样:

internal Product Save(Product product)
{
    // Read in the existing products
    var products = this.Retrieve();
    // Assign a new Id
    var maxId = products.Max(p => p.ProductID);

    product.ProductID = maxId + 1;
    products.Add(product);

    WriteData(products);

    return product;
}

internal Product Save(int id, Product product)
{
    // Read in the existing products
    var products = this.Retrieve();

    // Locate and replace the item
    var itemIndex = products.FindIndex(p => p.ProductID == product.ProductID);
    if (itemIndex > 0)
    {
        products[itemIndex] = product;
    }
    else
    {
        return null;
    }

    WriteData(products);
    return product;
}

这是正在使用的控制器的主要部分(使用Controller-As syntax

var vm = this;
vm.submit = function () {
    vm.message = "";
    if (vm.product.productID) {
        vm.product.$update({ id: vm.product.productID }, function (data { 
            console.log(data);
            vm.message = "Save Complete";
        });
    } else {
        vm.product.$save(function (data) {
            vm.originalProduct = angular.copy(data);
            vm.message = "Save Complete";
        });
    }
};

最后,productResource 是一个自定义服务,如下所示:

var productResource = function($resource, appSettings) {
    return $resource(appSettings.serverPath + "/api/Products/:id", null, {
        'update': { method: 'PUT' }
    });
}

我试图查看是否是 CORS 问题,但不是因为我在班级级别启用了它。

【问题讨论】:

  • 您的 post 和 put Web API 方法似乎没有返回任何内容。我认为他们应该回复?
  • @ChrisNevill 204: No Content 是我猜的默认响应,但他们不需要返回自定义响应来保存数据。这就是问题所在。
  • 奇怪的调试器没有达到你的断点。当您在 IIS express 或类似的东西中调试时,您确定客户端连接到正确的服务器,而不是 IIS?我一直在 Web API 中使用断点,它们确实有效。
  • @ChrisNevill 客户端使用正确的服务器。我没有遇到断点没有被命中的问题。到现在为止。

标签: javascript c# angularjs json asp.net-web-api


【解决方案1】:

请检查您的 API 是否实现了 CORS(跨源资源共享)

【讨论】:

  • 在班级级别启用。
【解决方案2】:

不应该

var itemIndex = products.FindIndex(p => p.ProductID == product.ProductID);

成为

var itemIndex = products.FindIndex(p => p.ProductID == id);

【讨论】:

  • 你在global.asax.cs 的路由怎么样,你能证明一下吗?既然你说代码甚至没有达到断点。
猜你喜欢
  • 2014-08-25
  • 2021-10-12
  • 2018-02-09
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多