405(不允许使用方法)使用Angular httpClient POST

时间:2019-06-27 10:15:31

标签: .net angular http post

这是我在Angular中用于发出POST请求的方法:

newMessage(m: Message) {
  this.http
    .post<any>('http://localhost:55820/api/message', m)
    .subscribe(res => (console.log(res)));
}

在带有asp.net WebApi 2的服务器端,我收到这样的请求:

[Route("api/message")]
[HttpPost]
public IHttpActionResult Create(Message message)
{
    return Ok("Ok");
}

使用PostMan,该请求可以正常工作,但是使用Angular,我得到了一个带有405状态代码的OPTIONS请求,而不是POST请求。我想念什么吗?谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用[FromBody]

 public IHttpActionResult Create([FromBody] Message message)

对于复杂类型(您自己的对象,例如:消息),Web API会尝试从HTTP请求的正文中读取值。

还请确保您在后端处理 CORS

答案 1 :(得分:0)

问题是我没有在服务器端配置CORS。当我在后端使用.net WebApi 2时,要解决的唯一步骤如下:

  1. 安装CORS(使用Nuget软件包管理器)
  

Microsoft.AspNet.WebApi.Cors安装包

  1. 将此行添加到WebApiConfig.cs
  

config.EnableCors();

  1. 在类声明之前将此行添加到控制器中
  

[EnableCors(来源:“ http://localhost:4200”,标题:   “ *”,方法:“ *”)]

在我的情况下,localhost:4200是我的前端地址。有关更多信息,请访问完整的教程:https://docs.microsoft.com/es-es/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

相关问题