SignalR CORS相同的原产地政策? [英] SignalR CORS same origin policy?

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

问题描述

当我运行有角度的应用程序时,我得到了一个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);
        }
    } 
}

这是我的忠实客户


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中显示

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天全站免登陆