asp.net-core - CORS 政策已被阻止我的子域
问题描述
我有一个相同的域,其中之一是没有前缀 www 的域。例如,
第一个域工作正常,因为它是默认域。但是当我执行 CRUD 或访问任何 api 服务时,第二个出现错误。
从源“ https://example.com ”访问“ https://www.example.com/hubCon/negotiate ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“*”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
试了一下微软发布的文章中的代码,还是不行。
我正在使用 .Net Core 2.2 版本。这是我的 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://example.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
.AllowCredentials();
});
});
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseCors(MyAllowSpecificOrigins);
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseHttpsRedirection();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<HubSignal>("/hubCon");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
}
所以,我不明白为什么该项目会出错。
感谢您的回答。
解决方案
您不能将 AllowAnyOrigin 与 AllowCredentials 一起使用。下面是一个允许使用 CORS 的通配符域的示例。
此代码在 ConfigureServices 中:
services.AddCors(options =>
{
options.AddPolicy("_AllowOrigin",
builder => builder
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithOrigins("https://localhost:44385", "https://*.azurewebsites.net", "http://*.azurewebsites.net")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
});
不要忘记在控制器中装饰您的操作:
[EnableCors("_AllowOrigin")]
推荐阅读
- javascript - 只允许没有空格或数字的英文字母?
- firebase - firebase 依赖项不再起作用
- sqlalchemy - SQLAlchemy - 在多个查询中使用相同的连接
- nginx - 例程:SSL23_GET_SERVER_HELLO:sslv3 警报握手失败
- audio - Webm 到 Flac 使用 FFMPEG
- azure - 在 Azure SQL 弹性池中创建数据库需要将近 10 分钟才能完成
- r - 如何使用我在 R 中的代码处理许多 txt 文件
- javascript - Axios 自定义实例无法与下一个 JS 一起正常工作
- reactjs - 如何在 react 和 typescript 中使用和传递 routeprops?
- c - 定时器在相同的设置下表现不同