我在发布到 aspnetcore api 时收到 415 http 错误结果。 如果我的端点标记为 [HttpPost] 而不是 [HttpDelete],则不会发生这种情况
在 aspnetcore api Controller 中:
[HttpDelete]
public async Task<IActionResult> Delete([FromBody]EntityViewModel vm)
{
在 Angular Controller 中:
var obj = new Object();
obj.atr1 = 1;
obj.atr2 = 2 ;
$http.post(route, obj)
.then(function (response) {
EntityViewModel.cs
public class EntityViewModel
{
public int Atr1 { get; set; }
public int Atr2 { get; set; }
}
最佳答案
先读完你的问题后,我有点困惑......
为什么使用$http.post
来发出DELETE请求?为什么 $http.delete
不用于此目的?然后我阅读了有关 AngularJS $http.delete
的更多信息,发现无法将正文发送到服务器。然后我问自己,为什么你应该能够在 DELETE 请求中发送正文。这里有一个很好的问题:Is an entity body allowed for an HTTP DELETE request? - 规范允许带有正文数据的 DELETE 请求。
长话短说......
ASP.NET Core 可以处理在正文中发送 JSON 数据的 DELETE 请求。所以 Controller 部分是有效的。
[HttpDelete]
public async Task<IActionResult> Delete([FromBody]EntityViewModel vm)
{
为了避免状态代码 415(不支持的媒体类型),将 header 字段 Content-Type
设置为 application/json
非常重要。我在使用 Postman 作为客户端的实验中忘记了这一点,并且也得到了 415 状态代码。
对于 AngularJS 部分,我建议使用
var obj = new Object();
obj.atr1 = 1;
obj.atr2 = 2 ;
$http(
{
method: 'DELETE',
url: route,
headers: {
'Content-Type': 'application/json'
},
data: obj
}
).then(function (response) {
关于angularjs - 使用 $http.delete 从 Angular 发布到 aspnetcore api 时出现不支持的媒体类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39298865/