我正在研究asp.net核心signalR。我想发出跨域请求。我有一个JavaScript客户端,当我将hubConnection设置为跨域signalR集线器时,则显示以下错误, 从源“ https://localhost:44373/chatHub/negotiate?token=12”对“ https://localhost:44381”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:无“ Access-Control-Allow-Origin”标头存在于请求的资源上。
JavaScript客户端代码
var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44373/chatHub?token="+12).build();
跨域信号器项目中的启动类
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("*")
.AllowCredentials();
}));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCors();
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseCors(builder =>
//{
// builder.WithOrigins("*")
// .AllowAnyHeader()
// .AllowAnyMethod()
// //.WithMethods("GET", "POST")
// .AllowCredentials();
//});
// ... other middleware ...
// app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub");
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
答案 0 :(得分:0)
在启动类中,取消注释以下行// app.UseCors("CorsPolicy");
您已经在ConfigureServices()
方法中构建了策略,现在您需要告诉应用在Configure()
方法中使用该策略
编辑:
为回应您的评论,如果您想在CORS政策中允许任何来源,
将.WithOrigins("*")
替换为.AllowAnyOrigin()
。