Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 信号器无法启动连接_C#_Asp.net Core_Signalr_Asp.net Core 2.0 - Fatal编程技术网

C# 信号器无法启动连接

C# 信号器无法启动连接,c#,asp.net-core,signalr,asp.net-core-2.0,C#,Asp.net Core,Signalr,Asp.net Core 2.0,我有一个angular应用程序和一个使用Signal的ASP.NET Core 2.2后端。启动连接时,我收到以下错误: Error: Failed to complete negotiation with the server: Error Error: Failed to start the connection: Error 点击localhost:5000/chatHub时的响应头- HTTP/1.1 204 No Content Date: Tue, 19 Feb 2019 08:5

我有一个angular应用程序和一个使用Signal的ASP.NET Core 2.2后端。启动连接时,我收到以下错误:

Error: Failed to complete negotiation with the server: Error
Error: Failed to start the connection: Error
点击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-

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();
    }
}
}
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()连接到HTML中的一个按钮。 但我永远也到不了那部分! 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
我试着在两端设置相同版本的信号器,但不起作用。这是不是.NET核心本身的问题? 我也尝试过使用Kestrel和IIS Express,但没有效果。
请在这一点上帮助我。

我可以通过查看此处的问题来解决此问题-

我将AllowAllPolicy移动到configure方法-

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