首页 > 解决方案 > SignalR CORS 同源策略?

问题描述

当我运行我的 Angular 应用程序时,我得到了一个 CORS,虽然我已经在我的 .NET 核心应用程序中启用了它,但常规的 http 请求似乎工作正常,只是 SignalR 我遇到了问题。任何建议将不胜感激。提前致谢。

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

这是我的 Startup.cs 文件

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

这是我的 ChatHub 课程

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

这是我的角度客户


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

}

更新,新错误:

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 :(

在铬它说

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 :(

标签: c#angular.net-corecorssignalr

解决方案


尝试app.UseHttpsRedirection();从您的Startup.cs中删除。

代码 307 是重定向响应。所以,这可能是问题的来源。

要么,要么看看关于使用 HTTPS 的一切。


推荐阅读