I have an angular app with a .net core web-api as the back end. the get request from the client works as expected and data from the server is fetched.
but when i try to post from the client to the server i get a 405 method not allowed error.
i have implemented the CORS middle ware found at this answer :
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 controller
[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);
}
}
Post model on server
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);
})
}
console error when trying to post to server:
what could be the reason for this error?
---Edit - found a solution--- in this answer
i added a base controller with the method
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
and now it works.