我试图在仅包含集线器类的Web应用程序中使用Azure SignalR服务.当我尝试从另一个域访问集线器时,我收到以下错误
“来自’https://localhost:44303‘的’https:// * / genericSocketHub / negotiate’访问XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否’Access-Control-Allow-Origin’标头出现在请求的资源上.“
在我的项目的startup.cs类中,我有:
`public class Startup
{
public IConfiguration Configuration {get; }
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.我的设置如下:
ConfigureServices
// 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?}"); });
注意确保以与上面示例相同的顺序添加各种实现.我无法解释为什么它对订单敏感,但这也是我的问题.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。