首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SignalR无法启动连接

问SignalR无法启动连接
EN

Stack Overflow用户
提问于 2019-02-19 17:18:58
回答 1查看 12.4K关注 0票数 3

我有一个angular应用程序,以及一个使用SignalR的ASP.NET Core2.2后端。启动连接时,我收到以下错误:

代码语言:javascript
复制
Error: Failed to complete negotiation with the server: Error
Error: Failed to start the connection: Error

命中localhost时的响应头:5000/chatHub-

代码语言:javascript
复制
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-

代码语言:javascript
复制
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-

代码语言:javascript
复制
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-

代码语言:javascript
复制
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()连接到HTML中的一个按钮。但我永远也不会说到那一步!OnInit()一直失败,即使接口返回的响应是204,应用程序也无法启动。回应-

代码语言:javascript
复制
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

我尝试在两端设置相同版本的SignalR,但不起作用。这是.NET核心本身的问题吗?我也尝试过使用Kestrel和IIS Express,但都无济于事。在这件事上请帮帮我。

EN

回答 1

Stack Overflow用户

发布于 2019-02-19 17:29:01

我可以通过这里的这个问题来解决这个问题-

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

我将AllowAllPolicy移到了configure方法中-

代码语言:javascript
复制
app.UseCors(builder =>
            {
                builder.WithOrigins("http://localhost:4200")
                .AllowAnyHeader().AllowAnyMethod().AllowCredentials();
            });
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54762611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档