aspnetcore: Signalr can't connect on latest RC1 Angular template

I simply create Angular spa template on VS 2022 RC1 and integrate SignalR but unfortunately it can’t connect to server over websocket or other connection options. I am not sure what is missed

I tested on previous template as well.

Here is full project to review SignalRTestApp

My program.cs

using Stratis.MarketPlace.Core;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddSignalR();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // 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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();


app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapHub<StoreHub>("hub");

app.MapFallbackToFile("index.html"); ;

app.Run();

Server files


    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
        private readonly IHubContext<StoreClientHub, IStoreClientHub> storeHub;

        public WeatherForecastController(IHubContext<StoreClientHub, IStoreClientHub> storeHub)
        {
            this.storeHub = storeHub;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            storeHub.Clients.All.SendMessage("heyooo!");

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

    public class StoreHub : Hub
    {
    }

    public class StoreClientHub : Hub<IStoreClientHub>
    {
        public async Task SendMessage(string message)
        {
            await Clients.All.SendMessage(message);
        }
    }

    public interface IStoreClientHub
    {
        Task SendMessage(string message);
    }

My front end files

proxy.conf.js

proxy.conf.js

const { env } = require('process');

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
  env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:8688';

const PROXY_CONFIG = [
  {
    context: [
      "/weatherforecast",
      "/hub"
   ],
    target: target,
    secure: false
  }
]

module.exports = PROXY_CONFIG;

store-hub.ts

import { Inject, Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder, HttpTransportType, IHttpConnectionOptions, LogLevel } from '@microsoft/signalr';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StoreHub {
  private connection: HubConnection;

  public onMessage = new Subject<string>();

  public onConnected: Promise<void>;

  constructor(@Inject('BASE_URL') baseUrl: string) {
    this.connection = new HubConnectionBuilder()
      .withUrl('/hub', {
        transport: HttpTransportType.WebSockets,
        logger: LogLevel.Trace
      })
      .build();

    this.onConnected = this.connection.start();

    this.connection.on("SendMessage", (message: string) => this.onMessage.next(message));
  }
}

and component file


import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { StoreHub } from './store-hub'

@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
  public forecasts: WeatherForecast[] = [];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string, private storeHub: StoreHub) {

    this.storeHub.onMessage.asObservable().subscribe(message => {
      console.log(message);
      alert(message);
    });

    this.storeHub.onConnected.then(() => {
      http.get<WeatherForecast[]>(baseUrl + 'weatherforecast').subscribe(result => this.forecasts = result);
    });
  }
}

interface WeatherForecast {
  date: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 24 (17 by maintainers)

Most upvoted comments

@Rick-Anderson can we add something to the docs here?

Ideally, point to the documentation for the http-proxy-middleware that I linked above, that way we make sure it stays current.

@javiercn this should be documented

UseWebSockets isn’t required for SignalR. It does that automatically