【发布时间】: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 中间件的链接。