SignalR CORS 同源策略? [英] SignalR CORS same origin policy?

查看:21
本文介绍了SignalR CORS 同源策略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的 Startup.cs 文件

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

这是我的 ChatHub 课程

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

这是我的 Angular 客户端

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

}

更新,新错误:

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

在 chrome 中它说

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

推荐答案

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

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

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

要么那样,要么看看对所有事情都使用 HTTPS.

Either that, or see about using HTTPS for everything.

这篇关于SignalR CORS 同源策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆