[英]JSON data not being saved in WebAPI
I'm following a Pluralsight course on AngularJS and WebAPI together.我正在一起学习关于 AngularJS 和 WebAPI 的 Pluralsight 课程。 I'm trying to save data being sent from the client to the server using
PUT
, but the data is not saving and I'm not getting any errors.我正在尝试使用
PUT
保存从客户端发送到服务器的数据,但数据没有保存,我没有收到任何错误。 Also, It doesn't event hit the correct server side code because the breakpoints are not being caught.此外,它不会触发正确的服务器端代码,因为断点没有被捕获。 I've tried to change the type of
HTTP
method, but I need this one.我试图改变
HTTP
方法的类型,但我需要这个。 The only thing being sent back is a "204: No Content"
code from the server.唯一被发回的是来自服务器的
"204: No Content"
代码。
This is how the PUT
and POST
methods look like.这就是
PUT
和POST
方法的样子。 Breakpoints in any of these methods will not be captured.任何这些方法中的断点都不会被捕获。
// 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
looks like this: 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;
}
This is the main part of the controller that is being used (using Controller-As syntax
:这是正在使用的控制器的主要部分(使用
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";
});
}
};
Finally, productResource is a custom service that looks like this:最后,productResource 是一个自定义服务,如下所示:
var productResource = function($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/Products/:id", null, {
'update': { method: 'PUT' }
});
}
I've tried to look to see if it's a CORS
problem, but it's not since I have it enabled at the class level.我试图查看它是否是
CORS
问题,但不是因为我在类级别启用了它。
请检查您的 API 是否实现了 CORS(跨源资源共享)
Shouldn't不应该
var itemIndex = products.FindIndex(p => p.ProductID == product.ProductID);
be是
var itemIndex = products.FindIndex(p => p.ProductID == id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.