gpt4 book ai didi

c# - 跨源请求在asp.net core signalR 中被阻止?

转载 作者:行者123 更新时间:2023-12-04 13:59:10 24 4
gpt4 key购买 nike

我正在研究asp.net核心signalR。我想进行跨域请求。我有一个javascript客户端,当我将hubConnection连接到跨域signalR集线器时,会显示以下错误,
访问 XMLHttpRequest ' https://localhost:44373/chatHub/negotiate?token=12 '来自原点' https://localhost:44381 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。

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();
}

最佳答案

在您的启动类(class)中取消注释以下行 // app.UseCors("CorsPolicy");
您已经在您的 ConfigureServices() 中构建了策略方法,现在您需要告诉应用程序在 Configure() 中使用该策略方法

编辑:

为了回应您的评论,如果您想在 CORS 政策中允许任何来源,
替换 .WithOrigins("*").AllowAnyOrigin()反而。

关于c# - 跨源请求在asp.net core signalR 中被阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com