【问题标题】:405 method not allowed error when making http post request from angular to web api从 Angular 到 Web api 发出 http post 请求时出现 405 方法不允许错误
【发布时间】:2021-09-21 23:22:24
【问题描述】:

我有一个 .net 核心 web-api 作为后端的 Angular 应用程序。 来自客户端的 get 请求按预期工作,并从服务器获取数据。

但是当我尝试从客户端发布到服务器时,我得到一个 405 方法不允许错误。

我已经实现了在 this answer 找到的 CORS 中间件:

    httpContext.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200");
    httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
    httpContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
    httpContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");

web-api 控制器

[Route("api/[controller]")]
[ApiController]
public class PostsController : ControllerBase
{
    [HttpGet]
    public ActionResult<List<Post>> Get()
    {
        return _repository.Get().ToList();
    }

    [HttpPost]
    public IActionResult Post([FromBody] Post post)
    {
        if (post == null)
        {
            return BadRequest();
        }
        _repository.Add(post);
        _repository.Save();
        return CreatedAtRoute("GetPostById", new { ID = post.Id }, post);
    }
}

在服务器上发布模型

   public class Post 
    {
        [Key]
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }

app.component.ts

  apiUrl = 'http://localhost:33633/api/posts';
  constructor(private http: HttpClient) {}

onCreatePost(postData: { title: string; content: string }) {

this.http.post(this.apiUrl, postData).subscribe(responseData =>
{
  console.log(responseData);
})
}
  onFetchPosts() {
    this.http.get(this.apiUrl).subscribe(responseData =>
    {
      console.log(responseData);
    })
  }

尝试发布到服务器时出现控制台错误:

这个错误的原因可能是什么?

---编辑 - 找到解决方案---this answer

我用该方法添加了一个基本控制器

public HttpResponseMessage Options()
{
  return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

现在它可以工作了。

【问题讨论】:

  • 您在后端服务中允许 CORS 吗?
  • 是的 - 正如我提到的我在后端使用的 CORS 中间件的链接。

标签: angular webapi


【解决方案1】:

表示你调用的 URL 不支持 HTTP 动词 OPTIONS

即使您只从代码中触发 POSTGET,此类请求也会自动触发。阅读https://stackoverflow.com/a/40497696/5389127

您必须在后端允许 OPTIONS 请求。

【讨论】:

  • 如果我在这里错了,请纠正我,但为了我的理解,如果选项请求在角度上失败 - 浏览器不会将发布请求发送到服务器。服务器上的 CORS 允许所有这些方法:POST、GET、PUT、PATCH、DELETE、OPTIONS。我怎样才能在 web api 控制器上允许 OPTIONS http 动词?
  • 你是对的,如果OPTIONS请求不成功,就不会再有其他请求了。我会编辑我的答案。如何在您的后端允许 OPTIONS 完全取决于您的后端技术/框架。我建议发布另一个专门针对您的后端的问题。
  • 感谢您提供相关信息丰富的答案,我已使用在另一个堆栈溢出答案中找到的解决方案编辑了我的帖子。
猜你喜欢
  • 2017-11-03
  • 2020-01-15
  • 2020-03-19
  • 2014-12-04
  • 2013-10-10
  • 2023-04-07
  • 1970-01-01
  • 2019-04-20
  • 2014-11-20
相关资源
最近更新 更多