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.