【发布时间】:2021-12-11 08:58:21
【问题描述】:
好吧,即使为 .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();
});
}
我遵循了每个教程、文档并得到了同样的结果:
- 我在 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");
}}
我搜索了很多,我什至做了一个相同的项目并且它有效。我不知道我在这里错过了什么。
【问题讨论】:
-
响应头是什么样子的。使用 Postman 之类的工具。
-
我对 .net 了解不多,但必须在服务器端和客户端处理 CORS。对于 Symfony 服务器,我们使用 github.com/nelmio/NelmioCorsBundle 处理 CORS 你可以搜索 .NET 的等价物吗?
标签: angular ionic-framework asp.net-core-webapi