【发布时间】:2021-05-11 00:58:51
【问题描述】:
我正在使用 Microsoft.ApsNetCore.Cors 2.2
“从源 'example.local' 访问 'exampleapi.local' 的 XMLHttpRequest 已被 CORS 策略阻止:
请求的资源上不存在“Access-Control-Allow-Origin”标头。”
我用这个设置设置:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.Configure<TokenSettings>(this.Configuration.GetSection("Tokens"));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Tokens:Issuer"],
ValidAudience = Configuration["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Tokens:SecurityKey"]))
};
});
services.AddMvc();
services.Configure<LdapConfig>(Configuration.GetSection("ldap"));
services.AddScoped<ILdapAuthenticationService, LdapAuthenticationService>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IProjectService, ProjectService>();
services.AddScoped<IProjectMembersService, ProjectMembersService>();
services.AddScoped<IJourneyUsersService, JourneyUsersService>();
services.AddScoped<IProjectRolesService, ProjectRolesService>();
services.AddScoped<IPmoGuardianService, PmoGuardianService>();
services.AddScoped<IHolidaysService, HolidaysService>();
services.AddScoped<IMailService, MailService>();
services.AddScoped<INotificationsService, NotificationsService>();
services.AddScoped<INotificationUsersService, NotificationUsersService>();
services.Configure<AWSConfigSes>(Configuration.GetSection("AWSSmtp"));
services.AddDbContext<JourneyContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("JourneyConnection")));
services.AddDbContext<TSMContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TSMConnection")));
services.AddDbContext<PmoGuardianContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PmoGuardianConnection")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMailService mail, INotificationsService not)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Recurrence recurrency = Recurrence.GetInstance(not);
//new TSMClockService(mail);
app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseMvc();
}
[Produces("application/json")]
[Route("api/Mail")]
[EnableCors("AllowSpecificOrigin")]
但它不起作用,总是我得到同样的错误
【问题讨论】:
-
CORS 标头必须由目标服务器设置,而不是 您的 服务器。 他们必须给你访问权限,而不是相反。
-
我在 2.2 中遇到了完全相同的问题
-
@Christian 你有运气解决这个问题吗?
-
还没有,我会尝试降级到 Cors,我希望能解决这个问题。和你?? @Capo
-
@ChristianHerrejon - 这对你来说可能是在黑暗中拍摄,但我终于能够通过添加
.. 到我服务器上的 webconfig。我也更新了我们的核心 v2 托管包,但这似乎没有效果。希望这会有所帮助!
标签: c# asp.net-web-api asp.net-core