4

I have a Web API that has 2 controllers and I have enabled Cors in my Startup class, here is my ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.AddAutoMapper();
        }

And here the Configure medhod:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors(
        options => options.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
    );

    app.UseHttpsRedirection();
    app.UseMvc();
}

Now, I have two controllers. When I make a GET request to this method, everything goes ok:

[Route("api/[controller]")]
[ApiController]
[EnableCors("MyPolicy")]
public class MovieController : ControllerBase
{
    public async Task<IActionResult> Get()
    {
        HttpClient httpClient = new HttpClient();

        var responseMessage = await httpClient.GetAsync("https://copafilmes.azurewebsites.net/api/filmes");

        if (!responseMessage.IsSuccessStatusCode) return null;

        var jsonResult = await responseMessage.Content.ReadAsStringAsync();

        return Ok(jsonResult);
    }

Now, when I try to make a POST to this one:

[Route("api/[controller]")]
[ApiController]
[EnableCors("MyPolicy")]
public class CupController : ControllerBase
{
    private readonly IMapper mapper;

    public CupController(IMapper mapper)
    {
        this.mapper = mapper;
    }

    [HttpPost]
    public IActionResult Post([FromBody] IEnumerable<MovieViewModel> moviesViewModel)
    {
        var movies = mapper.Map<IEnumerable<Movie>>(moviesViewModel).ToList();

        var cup = new Cup(movies);
        cup.Run();

        return Ok(cup.Id);
    }
}

Then I get the message in the browser console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://worldcupapi-gabs.azurewebsites.net/api/cup. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I am trying to make this post via a Vuejs simple app, you can try it here: https://codesandbox.io/s/j23np20663

Just select 8 cards (click on them and they'll become grey) and click on the "Submit" button.

gabsferreira
  • 3,089
  • 7
  • 37
  • 61
  • 3
    This is a surprisingly common [red herring](https://en.wikipedia.org/wiki/Red_herring) - The reason CORS headers aren't being set is because your server is throwing an error and returning a 500 status code. When an error is thrown, the CORS headers are *not set* (this is going to change in 2.2). You need to investigate why your server is throwing an error and ignore the CORS side of this for now. – Kirk Larkin Nov 05 '18 at 22:02
  • Yes, it was that @KirkLarkin! Want to answer so I can accept it? – gabsferreira Nov 07 '18 at 16:06
  • 1
    Same again here. There are many questions like this that come up so deleting is likely best now your problem is solved. – Kirk Larkin Nov 07 '18 at 16:35

1 Answers1

0

Serpent5 provided a valid answer above; I'm adding it as an answer because this is the first hit I got when searching on my CORS issue AND the cause of my issue isn't precisely what Serpent5 indicated, but expanding on his comment provides the answer.

Serpent5's answer basically says another error is preventing the server from responding properly (such as a 500 internal server error), but the browser development tools console shows a CORS error instead.

In my case it was because I didn't have https configured correctly on the server.

Mmm
  • 682
  • 9
  • 11