简体   繁体   English

SignalR 无法启动连接

[英]SignalR Failed to start the connection

I have an angular application along with an ASP.NET Core 2.2 backend that uses SignalR.我有一个 Angular 应用程序以及一个使用 SignalR 的 ASP.NET Core 2.2 后端。 When starting the connection, I receive the errors:开始连接时,我收到以下错误:

Error: Failed to complete negotiation with the server: Error
Error: Failed to start the connection: Error

Response Headers when hitting localhost:5000/chatHub-点击 localhost:5000/chatHub- 时的响应标头

HTTP/1.1 204 No Content
Date: Tue, 19 Feb 2019 08:52:52 GMT
Server: Kestrel
Access-Control-Allow-Headers: x-requested-with
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *

Startup.cs-启动.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 RealChat.Hubs;

namespace RealChat
{
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("AllowAllPolicy", builder => {
            builder
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowAnyOrigin();
        }));

        services.AddSignalR();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // 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
        {
            // 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("AllowAllPolicy");

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

        //app.UseHttpsRedirection();
        app.UseMvc();
    }
}
}

Chathub.cs-聊天室.cs-

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RealChat.Hubs
{
public class ChatHub : Hub
{
    public Task Send(string data)
    {
        return Clients.All.SendAsync("Receive", "Hello!!!");
    }
}
}

app-component.cs- app-component.cs-

import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr';
import * as signalR from '@aspnet/signalr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  private _hubConnection: HubConnection;
  msgs: string;

  constructor() { }

  ngOnInit(): void {
    this._hubConnection = new signalR.HubConnectionBuilder()
        .withUrl('http://localhost:5000/chatHub')
        .configureLogging(signalR.LogLevel.Information)
        .build();

    this._hubConnection.start().catch(err => console.error("SignalR startup error"));

    this._hubConnection.on('ReceiveMessage', (data) => {
        console.log(data);
    });
  }

  sendMessage(): void {
      console.log("Sending...\n");
       if (this._hubConnection)
          this._hubConnection.invoke('SendMessage', 'Test');
  }
}

SendMessage() is hooked to a button in HTML. SendMessage() 与 HTML 中的按钮挂钩。 But I can never get to that part!但我永远无法到达那个部分! OnInit() keeps failing and the application cannot start even when the response returned from the API is 204. Response- OnInit() 一直失败,即使从 API 返回的响应为 204,应用程序也无法启动。 响应-

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 OPTIONS http://localhost:5000/chatHub/negotiate
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
  CORS policy execution successful.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 0.6942ms 204

I've tried setting the same version of SignalR on both ends but it doesn't work.我试过在两端设置相同版本的 SignalR,但它不起作用。 Is it an issue of .NET Core itself?是 .NET Core 本身的问题吗? I've also tried using Kestrel and IIS Express but to no avail.我也尝试过使用 Kestrel 和 IIS Express 但无济于事。 Please help me on this one.请帮我解决这个问题。

I was able to solve the issue by looking at this issue here-我能够通过在此处查看此问题来解决该问题-

https://github.com/aspnet/SignalR/issues/2095#issuecomment-383899098 https://github.com/aspnet/SignalR/issues/2095#issuecomment-383899098

I moved the AllowAllPolicy to the configure method-我将 AllowAllPolicy 移至配置方法-

app.UseCors(builder =>
            {
                builder.WithOrigins("http://localhost:4200")
                .AllowAnyHeader().AllowAnyMethod().AllowCredentials();
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM