【发布时间】:2016-06-29 12:13:48
【问题描述】:
当我尝试使用 ASP.NET WEBAPI 将表单数据发布到 JSON 文件时,控制台中出现“没有 MediaTypeFormatter 可用于从媒体类型为‘text/plain’的内容中读取‘Product’类型的对象”错误
我没有在此处发布我的 html 文件,因为 html 中没有错误。发布请求时出现错误。
请帮助我,因为我现在卡住了,无法继续。
控制器调用 Post 方法:
var promisePost = crudService.post(Product);
promisePost.then(function (pl) {
$scope.ProductName = pl.data.ProductName;
//loadRecords();
}, function (err) {
console.log("Err" + err);
});
服务中的发布方法:
this.post = function (Product) {
var request = $http({
method: "post",
url: "http://localhost:50326/api/Products/",
data: Product,
contentType: 'application/json; charset=utf-8'
//Content-Type: application/json
});
return request;
}
WebApi 方法:
public void Post([FromBody]Product product)
{
ProductsRepository repository = new ProductsRepository();
var newproduct = repository.Save(product);
//return newproduct;
}
internal Product Save(Product product)
{
var products = this.Retrieve();
var maxId = products.Max(p => p.ProductId);
product.ProductId = maxId + 1;
products.Add(product);
WriteData(products);
return product;
}
private bool WriteData(List<Product> products)
{
var filePath = HostingEnvironment.MapPath(@"~/App_Data/Products.json");
var json = JsonConvert.SerializeObject(products, Formatting.Indented);
System.IO.File.WriteAllText(filePath, json);
return true;
}
【问题讨论】:
-
您的错误信息和您的代码不匹配,它抱怨内容是
text/plain,但根据您的邮政编码,它应该是application/json。您是否使用过 fiddler 之类的工具来检查实际的 POST 请求以验证它是否被正确传递? -
是的。我使用 Fiddler 来检查我的 POST 请求,因为我能够看到我的请求格式正确,并且我也可以看到它的 JSON。问题发生在 .then( ) 函数中,我猜 promisePost.then(function (pl) { $scope.ProductName = pl.data.ProductName; //loadRecords(); }
-
您检查了
Content-Type标头吗?我怀疑它发生在您的then中,因为这就是从 API 获得 500 错误的原因? -
控制台错误提示“POST localhost:50326/api/Products 500 (Internal Server Error)”
-
响应中的Content type是Content-Type: application/json; charset=utf-8 而在请求中它是 Content-Type: text/plain;charset=UTF-8。奇怪的是它是 text/plain 的,因为我们明确指定类型为 application/json
标签: c# angularjs asp.net-web-api