c# - 没有 MediaTypeFormatter 可用于从媒体类型为 'Product' 的内容中读取类型为 'text/plain' 的对象

标签 c# angularjs asp.net-web-api

当我尝试使用 ASP.NET WEBAPI 将我的表单数据发布到 JSON 文件时,我收到“没有 MediaTypeFormatter 可用于从媒体类型为‘text/plain’的内容中读取类型为‘Product’的对象”的错误消息

我不会在这里发布我的 html 文件,因为 html 中没有错误。发布请求时出现错误。

请帮助我,因为我现在卡住了,无法继续前进。

Controller 调用 Post 方法:

var promisePost = crudService.post(Product);        
promisePost.then(function (pl) {   
    $scope.ProductName = pl.data.ProductName;   
    //loadRecords();   
}, function (err) {   
    console.log("Err" + err);   
});    

服务中的 Post 方法:

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

最佳答案

尝试以这种方式发布您的数据:

$http.post(
   'http://localhost:50326/api/Products/',
   JSON.stringify(Product),
   { 
      headers: { 
         'Content-Type': 'application/json'
      }
   }
);

请注意,您不需要指定字符编码(我从未见过 Contet-Type header 中包含该部分。请参阅:What does "Content-type: application/json; charset=utf-8" really mean?)

另请注意,使用 JSON.stringify 将您的参数序列化为 JSON 以确保格式正确。

关于c# - 没有 MediaTypeFormatter 可用于从媒体类型为 'Product' 的内容中读取类型为 'text/plain' 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35987847/

相关文章:

asp.net-web-api - 在 Web API 中,当一个方法包含可空值类型作为参数时,如何重载 Get

asp.net - Route 属性上的 RouteOrder 属性在哪里?

c# - 索引文件大小限制

c# - 在 C# 或 C++ 中搜索另一个音频中的音频

angularjs - 如何将字符串变量绑定(bind)到日期选择器控件而不是日期对象?

javascript - 无法在 ngRepeat 中引用过滤数组 - AngularJS

c# - 检查 Web API 是否可用的好/正确方法是什么?

c# - C#中的对象和类有什么区别?

c# - 异步方法中的 Await 与 Task.Result

javascript - 以 Angular 加载测试图像源时出错