SignalR CORS same origin policy?

廉价感情. 提交于 2021-02-11 16:27:50

问题


When I run my angular app I get a CORS, although I've enabled it in my .NET core app, regular http requests seem to work fine, it's just with SignalR I'm having issues. Any suggestions would be much appreciated. Thanks in advance.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/chat/negotiate. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/chat/negotiate. (Reason: CORS request did not succeed).

[2019-07-06T19:34:25.061Z] Warning: Error from HTTP request. 0: . Utils.js:206
[2019-07-06T19:34:25.065Z] Error: Failed to complete negotiation with the server: Error Utils.js:203
[2019-07-06T19:34:25.070Z] Error: Failed to start the connection: Error Utils.js:203
Error while establishing connection :( chatComponent.component.ts:43:28

This is my Startup.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

// using WebApiServerApp.Searching;

namespace WebApiServerApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .WithOrigins("http://localhost:4200");
            }));1

            services.AddSignalR();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

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




            app.UseCors("CorsPolicy");
            app.UseHttpsRedirection();
            app.UseMvc();

             app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("/api/chat");
            });
        }
    }
}

This is my ChatHub class

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

using Microsoft.AspNetCore.SignalR;

namespace WebApiServerApp
{
    public class ChatHub : Hub
    {
        public Task SendToAll(string name, string message)
        {
             return Clients.All.SendAsync("ReceiveMessage", name, message);
        }
    } 
}

This is my angular client


import { Component, OnInit } from '@angular/core';
import { ITag } from '../Tag/tag';
import { TagComponent } from '../Tag/tag.component';
import { Router, ActivatedRoute, ParamMap, Params } from '@angular/router';
import { switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { IMessage } from './Message';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';



@Component({
  selector:'chat',
  templateUrl:"./chatComponent.component.html",
  //styleUrls: ['./tagSearch.component.css']
  // providers: [ ChatService ]
})

export class ChatComponent implements OnInit {

  hubConnection: HubConnection;

  message: string;
  nick: string;
  messages: string[] = [];

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {

    this.nick = window.prompt('Your name:', 'John');

    //http://localhost:5001/api/chat
    this.hubConnection = new HubConnectionBuilder().withUrl("http://localhost:5000/api/chat", {
      skipNegotiation: true,
      transport: HttpTransportType.WebSockets
    }).build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.log('Error while establishing connection :('));

      this.hubConnection.on('ReceiveMessage', (nick: string, receivedMessage: string) => {
        const text = `${nick}: ${receivedMessage}`;
        this.messages.push(text);
        });

    }


    public sendMessage(): void {
        this.hubConnection
          .invoke('SendToAll', this.nick, this.message)
          .catch(err => console.error(err));
    }

}

Update, new error:

Firefox can’t establish a connection to the server at ws://localhost:5000/api/chat. WebSocketTransport.js:85
[2019-07-06T20:06:31.730Z] Error: Failed to start the connection: null Utils.js:203
Error while establishing connection :(

In chrome it says

WebSocketTransport.js:85 WebSocket connection to 'ws://localhost:5000/api/chat' failed: Error during WebSocket handshake: Unexpected response code: 307
(anonymous) @ WebSocketTransport.js:85
Utils.js:203 [2019-07-06T20:31:51.740Z] Error: Failed to start the connection: null
push../node_modules/@aspnet/signalr/dist/esm/Utils.js.ConsoleLogger.log @ Utils.js:203
chatComponent.component.ts:46 Error while establishing connection :(

回答1:


Try removing app.UseHttpsRedirection(); from your Startup.cs.

Code 307 is a redirect response. So, that may be where the issue is coming from.

Either that, or see about using HTTPS for everything.



来源:https://stackoverflow.com/questions/56917125/signalr-cors-same-origin-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!