[英]Cross origin request blocked in asp.net core signalR?
我正在研究asp.net核心signalR。 我想进行跨域请求。我有一个JavaScript客户端,当我使hubConnection跨域signalR集线器时,然后出现以下错误,访问XMLHttpRequest的位置为https:// localhost:44373 / chatHub / negotiate?token = 12 'from origin'https:// localhost:44381 '已被CORS策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上没有'Access-Control-Allow-Origin'标头。
Javascript客户端代码
var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44373/chatHub?token="+12).build();
跨域Signalr项目中的启动类
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();
}
在启动类中,取消注释以下行// app.UseCors("CorsPolicy");
您已经在ConfigureServices()
方法中构建了策略,现在您需要告诉应用程序在Configure()
方法中使用该策略。
编辑:
作为对您的评论的回应,如果您想在CORS策略中允许任何来源,请将.WithOrigins("*")
替换为.AllowAnyOrigin()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.