我正在尝试在仅包含中心类的 Web 应用程序中使用 Azure SignalR 服务。当我尝试从另一个域访问集线器时,出现以下错误
“从来源‘https://localhost:44303’访问位于‘https://*/genericSocketHub/negotiate’的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无‘访问控制’ -Allow-Origin' header 出现在请求的资源上。”。
在我的项目的 startup.cs 类中,我有:
` 公共(public)类 Startup { 公共(public) IConfiguration 配置 { 得到;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(o => o.AddPolicy("Policy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}));
services.AddSignalR().AddAzureSignalR(Configuration.GetConnectionString("AzureSignalRConnectionString")).AddJsonProtocol(options => options.PayloadSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = new DefaultContractResolver()});
services.AddSingleton(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseCors("Policy");
app.UseAzureSignalR(routes =>
{
routes.MapHub<GenericSocketHub>("/genericSocketHub");
});
app.UseMvc();
}
}`
在不使用 Azure SignalR 服务的情况下,我没有遇到任何 CORS 问题
最佳答案
尝试将 .WithOrigins("[THE_DOMAIN_TO_UNBLOCK]");
添加到您的策略中:
services.AddCors(o => o.AddPolicy("Policy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("[THE_DOMAIN_TO_UNBLOCK]");
}));
还要确保您拥有最新版本的 Microsoft.Asure.SignalR
连同最新的 @aspnet/signalr
安装在服务器上安装在客户端上。
注意 signalr
npm 包与 Azure SignalR 不兼容。我通过艰难的方式学到了这一点..
以下适用于我的设置,即 Angular7、.NET CORE 2.1 和 Azure SignalR。我的设置如下所示:
配置服务
// Add CORS
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod()
.WithOrigins("http://localhost:4200");
});
});
// Add Azure SignalR
services.AddSignalR().AddAzureSignalR();
配置
app.UseCors("AllowAllOrigins");
app.UseAzureSignalR(routes =>
{
routes.MapHub<NextMatchHub>("/nextmatch");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "api/{controller=Home}/{action=Index}/{id?}");
});
注意 确保按照我上面的示例所示的相同顺序添加各种实现。我无法解释为什么它对订单敏感,但这对我来说也是一个问题。
关于c# - 如何在 Signalr Azure 服务中启用 Cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53558871/