在asp.net核心信号R中阻止交叉原始请求?

问题描述 投票:0回答:1

我正在研究asp.net core signalR。我想做跨域请求。我有一个javascript客户端,当我使hubConnection跨域signalR集线器,然后下面的错误显示,来自'https://localhost:44373/chatHub/negotiate?token=12'的'https://localhost:44381'访问XMLHttpRequest已被CORS策略阻止:响应预检请求未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。

Javascript客户端代码

var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44373/chatHub?token="+12).build();

跨域信号器项目中的启动类

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();
}
c# asp.net-core asp.net-core-signalr
1个回答
0
投票

在您的启动类中取消注释以下行// app.UseCors("CorsPolicy");

您已经在ConfigureServices()方法中构建了策略,现在您需要告诉应用程序在Configure()方法中使用该策略

编辑:

在回复您的评论时,如果您想在CORS政策中允许任何来源,请将.WithOrigins("*")替换为.AllowAnyOrigin()

© www.soinside.com 2019 - 2024. All rights reserved.