【发布时间】:2019-08-03 23:52:27
【问题描述】:
我正在研究 asp.net 核心 signalR。我想发出跨域请求。我有一个 javascript 客户端,当我将 hubConnection 连接到跨域 signalR 集线器时,会显示以下错误, 从源“https://localhost:44381”访问“https://localhost:44373/chatHub/negotiate?token=12”处的 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();
}
【问题讨论】:
-
你有两个
services.AddCors电话,有必要吗? -
我只使用一个 services.AddCors()
-
你有两个调用,一个在
services.AddMvc().方法的上方和下方。 -
哦,是的,不,我没有这两个电话
标签: c# asp.net-core asp.net-core-signalr