我正在研究asp.net核心signalR。我想提出跨域请求,我有一个javascript客户端,当我让hubConnection跨域signalR集线器时,下面的错误显示,CORS策略阻止了从“https://localhost:44373/chatHub/negotiate?token=12”到“https://localhost:44381”对XMLHttpRequest的访问:对飞行前请求的响应没有通过访问控制检查:请求的资源上没有“访问-控制-允许-原产地”标题。
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();
}发布于 2019-03-13 10:33:25
在您的启动类中,不要注释下面的行// app.UseCors("CorsPolicy");
您已经在ConfigureServices()方法中构建了策略,现在需要告诉应用程序在Configure()方法中使用该策略
编辑:
针对您的评论,如果您希望允许CORS策略中的任何源,请将.WithOrigins("*")替换为.AllowAnyOrigin()。
https://stackoverflow.com/questions/55139596
复制相似问题