3
Good morning, I created an API on. netCore 3 and I did all the tests enabling CORS and with POSTMAN I had no problems, but when trying to access API from another computer, I am being blocked by CORS. In startup.Cs, I enabled to pass any request.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
IdentityModelEventSource.ShowPII = true;
}
//app.UseHttpsRedirection();
//app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthentication();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
and no request:
[ApiController]
[Route("api/configs")]
public class ConfiguracaoController : ControllerBase
{
//Get funciona sem problemas
[HttpGet]
[Route("")]
public async Task<ActionResult<List<Configuracao>>> Get([FromServices] GeradorContext context)
{
var configs = await context.Configuracoes
.AsNoTracking()
.ToListAsync();
return Ok(configs);
}
//PUT ou outro não
[HttpPut("{Id}")]
public async Task<ActionResult<Configuracao>> Put([FromServices] GeradorContext context, int id, [FromBody] Configuracao configuracao)
{
try
{
var configs = await context.Configuracoes
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == id);
if (configs == null) return NotFound();
context.Update(configs);
await context.SaveChangesAsync();
return Created($"/api/configs/{configuracao.Id}", configuracao);
}
catch (DbUpdateConcurrencyException ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError, ex.ToString());
}
}
}
but I’m being blocked:
Access to XMLHttpRequest at 'http://192.168.0.24:8095/api/configs/2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
It just doesn’t happen in GET methods, for others(PUT, POST, DELETE) it happens.
Select the part of the connection code ?
– novic
Virgilio, thanks for the answer, I’m new to this world, when you say "connection code", I’d be the controller where I do the requests?
– user33105
yes ... where is that code
– novic
I edited and put him in question.
– user33105
on the other computer you are trying to access the api from the Postman? seems to be a browser response that ai, not from the back
– Lucas Miranda
In Postman I did tests on the same machine with different ports, on the other computer I’m trying to access the API with Chrome.
– user33105
The problem is probably using Chrome, if I’m not mistaken it blocks several features when using localhost
– Leandro Godoy Rosa
I believe that if there was a problem with the browser, no method would work and GET works.
– user33105