[英]Unsupported media type ASP.NET Core Web API
在前端,我使用 Angular 从表单中收集一些数据并将其发送到我的服务器端控制器。 如下图所示,我在控制器和服务上获取了数据 ($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);
}
您发送的标题是错误的。 您正在发送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 上的“ 内容协商”。
只需更换[FromBody]
至[FromForm]
在您的控制器。
这是一个 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 的更多详细信息,请参见此处。
我有这个接收控制器方法需要一个 [FromBody] 参数,但调用服务省略了参数。 在幕后猜测,期望(序列化)参数的控制器方法期望请求内容类型(MIME)为 application/json - 但 HttpClient 不带参数调用 POST/PUT 不会传递这个(可能只是文本/html) - 因此我们得到 415 'Unsupported Media Type'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.