I have a ASP.NET Core webapi and im trying to post to it with an Angular6 app. On the GET request it works fine, but when I try to make a post I always get this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access
What I tried. Startup.cs:
services.AddMvc();
services.AddCors(options => options.AddPolicy("AllowCors",
builder =>
{
builder
.AllowAnyOrigin()
.WithMethods("GET", "PUT", "POST", "DELETE", "OPTIONS")
.AllowAnyHeader();
}));
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowCors");
app.UseMvc();
}
And In my controller:
[Route("api/[controller]")]
[EnableCors("AllowCors")]
public class SearchController : Controller {
//code
//Here I get the error
[HttpPost("{term}")]
public async Task SaveSearch([FromBody]dynamic request, string term)
{
_searchRepository.SaveSearch(term, request);
}
}
On Angular app:
saveSearch(term: string, res:any) {
this.http.post(`${this.serviceEndpoint}${term}`, {
term: term, origin: res.countryCode, request: res
}).subscribe();
});
EDIT:
I put the OPTIONS method too, but still getting the error.
services.AddCors(...)is there one where you haveapp.UseCors(...);underConfigure()?.WithMethods("GET", "PUT", "POST", "DELETE", "OPTIONS")