【发布时间】:2020-07-11 07:25:13
【问题描述】:
我正在尝试使用 Cors 在 Angular 和我的 .net API 之间建立连接。我不断收到此错误:
localhost/:1 Access to XMLHttpRequest at 'https://localhost:44378/api/OffRec' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
为了修复这个错误。我在 ConfigureServices 中添加了 addCors,在 Configure 中添加了 userCors,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
{
builder.WithOrigins(new string[] { "http://localhost:4200" , "https://localhost:44378/api/offrec" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin");
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers();
services.AddDbContext<db_recloadContext>();
}
我的配置方法只是使用Cors:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
// app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
我的 api 有一个非常简单的代码,它返回一个字符串,当我运行我的 api 时,它工作正常。
过去 2 天我一直在努力解决这个错误。任何提示或帮助将不胜感激。
这是我根据下面的答案尝试过的仍然得到同样的错误:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
{
builder.WithOrigins(new string[] { "http://localhost:4200" , "https://localhost:44378/api/offrec" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin:*");
});
});
下面是错误的图片:
下面是我的api:
namespace RecLoad.Controllers
{
[Route("api/[controller]")]
[EnableCors("AllowAnyCorsPolicy")]
[HttpGet]
public ActionResult<string> Get()
{
return "This is a test";
}
【问题讨论】:
-
所以从技术上讲,错误信息和你的问题标题完全相反!?
-
检查浏览器的 URL 并确保来源与列表中的来源之一匹配。