不受支持的媒体类型ASP.NET Core Web API [英] Unsupported media type ASP.NET Core Web API
问题描述
在前端,我使用Angular从表单收集som数据并将其发送到我的服务器端控制器.如下图所示,我在控制器和服务上获取了数据($ scope.newData),但是当数据到达服务器时,出现以下错误:不支持的媒体类型",并且newData为空.
On the front-end i use Angular to collect som data from the form and send it to my server-side controllers. As the image shows below, i get the data ($scope.newData) on my controller and service, but when it reaches the server, i get the following error: "Unsupported media type" and my newData is empty.
我的控制器:
// Create new salesman
$scope.addSalesman = function (newData) {
console.log("Controller");
console.log($scope.newData);
myService.addNewSalesman($scope.newData).then(function (data) {
console.log(data);
}, function (err) {
console.log(err);
});
};
我的服务:
addNewSalesman: function (newData) {
console.log("service");
console.log(newData)
var deferred = $q.defer();
$http({
method: 'POST',
url: '/api/Salesman',
headers: { 'Content-type': 'application/json' }
}, newData).then(function (res) {
deferred.resolve(res.data);
}, function (res) {
deferred.reject(res);
});
return deferred.promise;
}
我的推销员模型:
public class Salesman
{
public int SalesmanID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string BirthDate { get; set; }
public int Phone { get; set; }
public string Adress { get; set; }
public string City { get; set; }
public int Postal { get; set; }
public string Role { get; set; }
}
我的服务器端控制器:
[Route("api/[controller]")]
public class SalesmanController : Controller
{
private readonly DataAccess _DataAccess;
public SalesmanController()
{
_DataAccess = new DataAccess();
}
[HttpPost]
public IActionResult PostSalesman([FromBody] Salesman newData)
{
return Ok(newData);
}
推荐答案
您发送的标头错误.您正在发送Content-Type: application/json
,但是您必须发送Accept: application/json
.
The header you are sending is wrong. You are sending Content-Type: application/json
, but you have to send Accept: application/json
.
Content-Type: application/json
到客户端,客户端必须发送Accept
来告诉服务器它接受哪种响应类型.
Content-Type: application/json
is what the server must send to the client and the client must send Accept
to tell the server which type of response it accepts.
addNewSalesman: function (newData) {
console.log("service");
console.log(newData)
var deferred = $q.defer();
$http({
method: 'POST',
url: '/api/Salesman',
headers: { 'Accept': 'application/json' }
}, newData).then(function (res) {
deferred.resolve(res.data);
}, function (res) {
deferred.reject(res);
});
return deferred.promise;
}
应该这样做.另请参阅MDN上的"内容协商".
Should do it. Also see "Content negotiation" on MDN.
这篇关于不受支持的媒体类型ASP.NET Core Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!