【问题标题】:Error trying to connect to asp.net core signalr hub from Angular App尝试从 Angular App 连接到 asp.net core signalr hub 时出错
【发布时间】:2020-12-11 14:16:48
【问题描述】:

我有一个使用 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-signal,但都给了我同样的错误。 安装在服务器端的包是这个 “***Common”最近安装只是为了检查。不确定是否需要。

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

【问题讨论】:

  • 如果打包解决方案不起作用,请在启动时添加更多服务器配置代码。
  • 肯定会添加更多代码
  • 我添加了 startup.cs 文件

标签: angular asp.net-core signalr asp.net-core-signalr azure-signalr


【解决方案1】:

问题是这条线。

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

我在添加 signalR 之前包装了响应,而 signalR 没有正确提取该响应

这种安排对我有用。

【讨论】:

  • 拯救了我的一天:心:
【解决方案2】:

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

【讨论】:

  • 试过了。它有同样的错误。然后我搬回了aspnet。我会再试一次,但很确定错误是一样的。
  • npm 页面表明它是向后兼容的,所以从理论上讲,它不应该有所作为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 2016-12-18
  • 1970-01-01
  • 2020-08-23
  • 2020-06-30
  • 2021-08-15
  • 2019-08-18
相关资源
最近更新 更多