0

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.

6
  • I see services.AddCors(...) is there one where you have app.UseCors(...); under Configure()? Commented May 15, 2018 at 15:55
  • 1
    .WithMethods("GET", "PUT", "POST", "DELETE", "OPTIONS") Commented May 15, 2018 at 16:00
  • @penleychan yes! i have it, edited the OP Commented May 15, 2018 at 16:02
  • @RitwickDey I put the method OPTIONS, and still getting the error. Commented May 15, 2018 at 16:05
  • @RitwickDey sorry, its working now. Commented May 15, 2018 at 16:09

1 Answer 1

1

CORS means that you have to configure Access-Control-Allow-Origin with a value of * (for all) on your application server.

Since Angular is making pre-flight requests, I highly recommend to add OPTIONS to the Access-Control-Allow-Methods configuration.

This is highly depended on the servers you're using, but you didn't state how you served your application. ;)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.