Chr*_*jon 5 c# asp.net-web-api asp.net-core
我正在使用Microsoft.ApsNetCore.Cors 2.2
“ CORS策略已阻止从来源“ example.local”访问“ exampleapi.local”处的XMLHttpRequest:在请求的资源上不存在“ 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")]
Run Code Online (Sandbox Code Playgroud)
但这不起作用,总是出现相同的错误
小智 1
艾米的评论是对的。CORS 标头需要由目标服务器而不是您的服务器设置。
如果您尝试连接到不同端口上的 API,但在同一 IP 地址上本地运行(最常见的示例是 localhost:<> 尝试 ping localhost<> 等),您经常会发现 CORS 问题。
如果您尝试使用 Google Chrome 在本地计算机上运行此程序,您可以下载以下扩展程序,该扩展程序将允许您打开和关闭 CORS 规则,以便您可以在本地进行测试: 允许 CORS:Access-Control-Allow-Origin
| 归档时间: |
|
| 查看次数: |
2495 次 |
| 最近记录: |