在前端,我使用Angular从表单中收集som数据并将其发送到我的服务器端控制器。如下图所示,我在我的控制器和服务上获取数据($ scope.newData),但当它到达服务器时,我收到以下错误:"不支持的媒体类型"我的newData是空的。
我的控制器:
// 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);
}
答案 0 :(得分:6)
您发送的标头错误。您要发送Content-Type: application/json
,但必须发送Accept: application/json
。
Content-Type: application/json
是服务器必须发送给客户端的内容,客户端必须发送Accept
告诉服务器它接受哪种类型的响应。
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上的“Content negotiation”。
答案 1 :(得分:6)
这是一个CORS问题。
在开发过程中,可以安全地接受来自所有来源的所有http请求方法。将以下内容添加到startup.cs:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//Accept All HTTP Request Methods from all origins
app.UseCors(builder =>
builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
app.UseMvc();
}
有关CORS的详细信息,请参阅here。
答案 2 :(得分:5)
只需将控制器中的[FromBody]
替换为[FromForm]
。
答案 3 :(得分:0)
我在接收控制器方法需要一个 [FromBody] 参数的地方遇到了这个问题,但调用服务省略了该参数。 在幕后猜测,期望(序列化)参数的控制器方法期望请求内容类型(MIME)为 application/json - 但 HttpClient 不带参数调用 POST/PUT 不会传递这个(可能只是文本/html) - 因此我们得到 415 'Unsupported Media Type'。