IONIC/Angular.NET 6 中的 CORS 问题

CORS issue in .NET 6 with IONIC/Angular

嗯,即使为 .NET 6 中的后端启用所有可能的 CORS,我也无法通过 IONIC/Angular 服务调用端点。

我在后端的代码(都按预期在 postman 上运行):

[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();
    });
}

我按照每个教程、文档进行操作并得到了同样的结果:

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");
}}

我搜索了很多,我什至做了一个相同的项目并且它有效。我不知道我在这里错过了什么。

  1. 启用带扩展的 cors(对于 firefox:https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/?utm_source=addons.mozilla.org&utm_medium=referral&utm_content=search)您也可以尝试 chrome,但由于 chrome 更受限制,请首先在 firefox 上尝试。 如果此解决方案有效,则您的问题出在后端。您必须在那里启用 CROS。

  2. 如果扩展程序无法正常工作,它将向您提供确切的错误信息。