Ошибка при попытке подключиться к концентратору сигналов ядра asp.net из приложения Angular

У меня есть приложение asp.net core 3.1, которое использует Microsoft.AspNetCore.SignalR 1.1.0 и Microsoft.Azure.SignalR

в сигнале запуска настроен так

 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-signal, но все они давали мне такую ​​же ошибку. пакеты, установленные на стороне сервера, это *** Common был установлен недавно просто для проверки. не уверен, требуется ли это. введите описание изображения здесь

Обновление 2, я удалил Azure Signalr и просто использовал Microsoft.AspNetCore.SignalR 1.1.0 на стороне сервера и @ microsoft / signalr @ latest на стороне клиента. но это та же ошибка.


person Raas Masood    schedule 22.08.2020    source источник
comment
Если пакетное решение не работает, добавьте дополнительный код конфигурации вашего сервера при запуске.   -  person Kiril1512    schedule 22.08.2020
comment
Конечно, я добавлю немного кода   -  person Raas Masood    schedule 22.08.2020
comment
я добавил файл startup.cs   -  person Raas Masood    schedule 23.08.2020


Ответы (2)


Проблема была в этой строке.

app.UseApiResponseAndExceptionWrapper(new AutoWrapperOptions { ShowStatusCode = true, UseApiProblemDetailsException = true, IsDebug = true, EnableExceptionLogging = true, LogRequestDataOnException = true }); //

Я оборачивал ответ перед добавлением signalR, который не был правильно принят signalR

эта договоренность сработала для меня. введите описание изображения здесь

person Raas Masood    schedule 24.08.2020
comment
Спас мой день: сердце: - person Ubaid Ullah; 21.05.2021

Прежде всего, не используйте @aspnet/signalr, потому что он устарел. Правильный пакет для использования - @microsoft/signalr.

person Kiril1512    schedule 22.08.2020
comment
Пробовал. Была такая же ошибка. Затем я вернулся к aspnet. Я попробую еще раз, но почти уверен, что ошибка была такой же. - person Raas Masood; 22.08.2020
comment
Страница npm для этого указывает, что он обратно совместим, поэтому теоретически это не должно иметь значения. - person Captain Prinny; 24.05.2021