尝试从Angular App连接到ASP.NET Core Signalr Hub时出错

问题描述

我有一个使用Microsoft.AspNetCore.SignalR 1.1.0和Microsoft.Azure.SignalR的asp.net core 3.1应用程序

在启动信号中这样设置

 services.AddSignalR().AddAzureSignalR("Endpoint=https://xxxxx.service.signalr.net;AccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=;Version=1.0;");
  ...
       app.UseAzureSignalR(routes =>
        {
            routes.MapHub<TransactionHUB>("/updateall");
        });

在已安装的角度应用程序中

npm install @ aspnet / signalr

我正在开始这样的连接

 public startConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
        .withUrl('https://localhost:44391/updateall')
        .build();
    this.hubConnection
        .start()
        .then(() => console.log('Connection started'))
        .catch(err => console.log('Error while starting connection: ' + err));
}

应用程序加载时出现错误

错误:无法启动连接:错误:服务器不支持客户端支持的任何传输。

更新

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Threading.Tasks;
        using autowrapper;
        using Entities;
        using Infrastructure;
        using Infrastructure.Contracts;
        using Microsoft.AspNet.OData.Builder;
        using Microsoft.AspNet.OData.Extensions;
        using Microsoft.AspNetCore.Builder;
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.AspNetCore.HttpsPolicy;
        using Microsoft.AspNetCore.Mvc;
        using Microsoft.EntityFrameworkCore;
        using Microsoft.Extensions.Configuration;
        using Microsoft.Extensions.DependencyInjection;
        using Microsoft.Extensions.Hosting;
        using Microsoft.Extensions.Logging;
        using Microsoft.OData;
        using Microsoft.OData.Edm;
        using Services;
        using Services.Contracts;

        namespace BBBankApi
        {
            public class Startup
            {
                public Startup(IConfiguration configuration)
                {
                    Configuration = configuration;
                }

                // readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

                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(options =>
                  //  {
                  //      options.AddPolicy(MyAllowSpecificOrigins,//      //builder =>
                  //      //{
                  //      //    builder.WithOrigins("http://localhost:4200");
                  //      //});
                  //  builder => builder.AllowAnyOrigin()
                  //.AllowAnyMethod()
                  //.AllowAnyHeader());
                  //  });
                    services.AddCors(options =>
                    {
                        options.AddPolicy("CorsPolicy",builder => builder
                        .WithOrigins("http://localhost:4200")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
                    });
                    //services.Configure<ApiBehaviorOptions>(options =>
                    //{
                    //    options.SuppressModelStateInvalidFilter = true;
                    //});// stopping default asp.net core model state validation
                    services.AddControllers(config =>
                    {
                        config.Filters.Add(new ModelValidationCheckFilter());
                    });
                    services.AddScoped<ITransactionService,TransactionService>();
                    services.AddScoped<IUnitOfWork,UnitOfWork>();
                    services.AddScoped<DbContext,BBBankContext>();
                    services.AddScoped<ITransactionRepository,TransactionRepository>();
                    services.AddScoped(typeof(IRepository<>),typeof(sqlServerRepository<>));
                    services.AddScoped<IAccountService,AccountService>();
                    var connection = @"Server=(localdb)\mssqllocaldb;Database=xxxxx;Trusted_Connection=True;ConnectRetryCount=0";
                    services.AddDbContext<BBBankContext>(
            b => b.UsesqlServer(connection)
                    .UseLazyLoadingProxies(false)  //Install-Package Microsoft.EntityFrameworkCore.Proxies -Version 3.1.1
                                                   //Lazy Loading means that the navigation properties will be loaded automatically as soon as they are called
                                                   //if true the odata expand will work on Transactions as well. 
                    );

                    services.AddOData();
                    services.AddODataQueryFilter();

                    services.AddMvc(options =>
                    {
                        options.EnableEndpointRouting = false;
                    }).AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

                    services.AddSignalR().AddAzureSignalR("Endpoint=https://xxxxxx.service.signalr.net;AccessKey=xxxxxxxxxxxx+9xdFN63uV8mPjIakR2ZWoJhmTk=;Version=1.0;");
                }

                // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
                public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
                {
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
                    app.UseApiResponseAndExceptionWrapper(new autowrapperOptions { ShowStatusCode = true,UseApiProblemDetailsException = true,IsDebug = true,EnableExceptionLogging = true,LogRequestDataOnException = true }); //
                    // app.UseCustomExceptionMiddleware();
                    // was using this middleware only for logging. but do we really need it if autowrapper has its own middleware 
                    // that logs using default logging configuration of asp.net core.
                    app.UseCustomLogginMiddleware();
                   // app.UseCors(MyAllowSpecificOrigins);
                    app.UseCors("CorsPolicy");
                    app.UseMvc(b =>
                    {
                        b.MapODataServiceRoute("odata","odata",GetEdmModel());
                    });
                    app.UseHttpsRedirection();



                    app.UseRouting();

                    app.UseAuthorization();

                    app.UseEndpoints(endpoints =>
                    {
                        endpoints.MapControllers();

                    });

                    app.UseAzureSignalR(routes =>
                    {
                        routes.MapHub<TransactionHUB>("/updateall");
                    });
                }

                private static IEdmModel GetEdmModel()
                {
                    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
                    builder.EnableLowerCamelCase();
                    builder.EntitySet<Account>("Accounts").EntityType.Count().Page(50,3).Expand().Filter().Select().OrderBy();
                    builder.EntitySet<User>("Users");
                    builder.EntitySet<Transaction>("Transactions");
                    return builder.GetEdmModel();
                }
            }
        }

更新2

我也尝试过使用不同版本的Microsoft信号,但是都给了我同样的错误。 服务器端安装的软件包是这个 最近安装了“ *** Common”只是为了检查。不知道是否需要。

enter image description here

更新2 删除了Azure Signalr,仅在服务器端使用Microsoft.AspNetCore.SignalR 1.1.0,在客户端使用@ microsoft / signalr @ latest。但它是同样的错误

解决方法

首先,不要使用@aspnet/signalr,因为它已经过时了。正确使用的软件包是@microsoft/signalr

,

问题是这一行。

Model: "functional_3"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_token (InputLayer)        [(None,300)]        0                                            
__________________________________________________________________________________________________
masked_token (InputLayer)       multiple             0           input_token[0][0]                
__________________________________________________________________________________________________
tf_distil_bert_model (TFDistilB ((None,300,768),)  66362880    masked_token[1][0]               
__________________________________________________________________________________________________
tf_op_layer_strided_slice (Tens multiple             0           tf_distil_bert_model[1][0]       
__________________________________________________________________________________________________
efficientnetb5_input (InputLaye [(None,456,3) 0                                            
__________________________________________________________________________________________________
batch_normalization (BatchNorma (None,768)          3072        tf_op_layer_strided_slice[1][0]  
__________________________________________________________________________________________________
efficientnetb5 (Functional)     (None,15,2048) 28513527    efficientnetb5_input[0][0]       
__________________________________________________________________________________________________
dense (Dense)                   (None,256)          196864      batch_normalization[1][0]        
__________________________________________________________________________________________________
global_average_pooling2d (Globa (None,2048)         0           efficientnetb5[1][0]             
__________________________________________________________________________________________________
dense_1 (Dense)                 (None,140)          35980       dense[1][0]                      
__________________________________________________________________________________________________
dense_3 (Dense)                 (None,140)          286860      global_average_pooling2d[1][0]   
__________________________________________________________________________________________________
concatenate (Concatenate)       (None,280)          0           dense_1[1][0]                    
                                                                 dense_3[1][0]                    
__________________________________________________________________________________________________
dense_4 (Dense)                 (None,100)          28100       concatenate[0][0]                
__________________________________________________________________________________________________
dropout_20 (Dropout)            (None,100)          0           dense_4[0][0]                    
__________________________________________________________________________________________________
dense_5 (Dense)                 (None,20)           2020        dropout_20[0][0]                 
==================================================================================================
Total params: 95,429,303
Trainable params: 30,120
Non-trainable params: 95,399,183

i在添加signalR之前包装了响应,而signalR无法正确拾取

这种安排对我有用。 enter image description here