Home > Net >  CORS issue in .NET 6 with IONIC/Angular
CORS issue in .NET 6 with IONIC/Angular

Time:11-02

Well, even enabling all the possible CORS for the backend which is in .NET 6 I can't call the endpoints via IONIC/Angular service.

My code in backend (It's all working on postman as expected):

  • Some Controllers Methods:
[HttpGet("ano/{year:int}")]
public ActionResult<Result> GetByYear(int year){
    try{
        if (year >= 2015 && year <= 2021){
            var result = _service.GetByYear(year);
            return Ok(result);
        }
        return BadRequest("The year must be between 2015 to 2021.");
    }catch (Exception ex){
        return Problem(ex.Message);
    }
}

[HttpGet("cidade/nomes")]
public ActionResult<IEnumerable<string>> GetCityNames(){
    try{
        return Ok(_service.GetAllCityNames());
    }catch (Exception ex){
        return Problem(ex.Message);
    }
}

// My startup class:
public void ConfigureServices(IServiceCollection services){
    services.AddSingleton<IXlsxAcessor,XlsxAcessor>();            
    services.AddControllers();           
    services.AddSwaggerGen(c => {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Domestic.Violence.API", Version = "v1" });
});

services.AddCors(option => {
    option.AddDefaultPolicy(builder =>{
          builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
        });
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
    if (env.IsDevelopment()){
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Domestic.Violence.API v1"));
    }
    app.UseHttpsRedirection();            
    app.UseRouting();
    app.UseCors();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>{
        endpoints.MapControllers();
    });
}

I followed every tutorial, documentation and got the same thing:

Picture of the error

  • My service in ionic/angular:
export class ApiService {
    constructor(private httpClient: HttpClient) { }
    private url: string = "http://localhost:5000/api/violence-statistics";

    public GetAllCityNames() : Observable<string[]>{
           return this.httpClient.get<string[]>(this.url   "/cidade/nomes");
}}

I searched a lot, I even did a project as the same and it works. I don't know what I am missing here.

CodePudding user response:

  1. Enable cors with extension (For firefox: https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/?utm_source=addons.mozilla.org&utm_medium=referral&utm_content=search) You can try for chrome too, but since chrome is more restircted try firstly on firefox. If this solution works than your problem is on backend. You have to enable CROS there.

  2. If extension not working it will give you the exact error what is happening.

  • Related