最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

SignalR in .NET 9 and Angular v19 errors - Websockets issues - Stack Overflow

programmeradmin3浏览0评论

Here are the errors from Chrome debugger screen:

[2025-03-14T07:24:52.776Z] Information: Normalizing '/downloadHub' to 'https://127.0.0.1:63349/downloadHub'.
Utils.js:148

[2025-03-14T07:28:52.849Z] Information: (WebSockets transport) There was an error with the transport.
chunk-J25FJFZE.js:49

[2025-03-14T07:28:52.854Z] Error: Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.

I have no ideas how to resolve this error since SignalR is new to me. I googled this issue and tried to correct my code but it doesn't solve anything.

My code link is

Any input leads to solve this issue is very appreciated.

Thanks.

Here are the errors from Chrome debugger screen:

[2025-03-14T07:24:52.776Z] Information: Normalizing '/downloadHub' to 'https://127.0.0.1:63349/downloadHub'.
Utils.js:148

[2025-03-14T07:28:52.849Z] Information: (WebSockets transport) There was an error with the transport.
chunk-J25FJFZE.js:49

[2025-03-14T07:28:52.854Z] Error: Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.

I have no ideas how to resolve this error since SignalR is new to me. I googled this issue and tried to correct my code but it doesn't solve anything.

My code link is https://github/d052057/YtSharp

Any input leads to solve this issue is very appreciated.

Thanks.

Share Improve this question edited Mar 14 at 9:13 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 14 at 8:13 D052057D052057 1852 silver badges11 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 0

I add setTimeout in below code, and it works properly. I am not experts in Angular. Adjustments to Angular-related codes require collaboration between you and your team.

  async ngOnInit(): Promise<void>  {
    // Subscribe to progress updates from SignalR
    this.signalRService.progress$.subscribe(({ downloadId, status }) => {
      setTimeout(() => {
        if (downloadId === this.currentDownloadId) {
          console.log("Updating downloadStatus signal with:", JSON.stringify(status));
          this.downloadStatus.set({ ...status });

          // Update UI with latest output
          if (status.output && status.output.length > this.output().length) {
            this.output.set([...status.output]);
          }
          this.cdr.detectChanges();
          // Check if download is completed
          if (status.isCompleted) {
            this.isDownloading = false;

            if (status.isSuccessful) {
              this.showSuccessMessage(status.filePath);
            } else {
              this.showErrorMessage('Download failed', status.errorMessage);
            }
          }
        }
      }, 500);
      
    });
  }

After testing, I determined that this problem only occurs during vs2022 debugging. If this application is published, this problem will not occur.

The reason is that SPA uses proxy configuration when debugging in VS2022. So when it starts, we can see that the angular application is running on port 63349 and the api project is running on port 7217.

If you are still in the development stage, you can explicitly specify the url in the angular project as .withUrl("https://localhost:7217/downloadHub"). And we also need to enable cors feature as well.

Here is the detailed steps.

signalr.service.ts

  private apiHub = "https://localhost:7217/downloadHub";
  constructor() {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(this.apiHub) // Match the SignalR hub URL on the server
      .withAutomaticReconnect()
      .configureLogging(signalR.LogLevel.Debug)
      .build();
  }

Program.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json.Serialization;
using YtSharp.Server;
using YtSharp.Server.services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Add CORS Settings
builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", policy =>
{
    policy
        .WithOrigins("https://127.0.0.1:63349", "https://localhost:63349")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
}));
builder.Services.AddSignalR();
builder.Services.AddDirectoryBrowser();
builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddScoped<IYtSharpService, YtSharpService>();
builder.Services.AddControllers().AddNewtonsoftJson(
               options =>
               {
                   options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                   options.SerializerSettings.TypeNameHandling = TypeNameHandling.None;
                   options.SerializerSettings.Formatting = Formatting.Indented;
               }
               )
               .AddXmlSerializerFormatters()
               .AddJsonOptions(options =>
               {
                   options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                   options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
               })
               .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()
            );

var app = builder.Build();

app.UseHttpsRedirection();

app.UseDefaultFiles();
app.UseStaticFiles();
var MimeProvider = new FileExtensionContentTypeProvider();
MimeProvider.Mappings[".flac"] = "audio/flac";
MimeProvider.Mappings[".flv"] = "video/x-flv";
MimeProvider.Mappings[".mkv"] = "video/mp4";
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(@"c:/medias"),
    RequestPath = "/medias",
    ContentTypeProvider = MimeProvider
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    FileProvider = new PhysicalFileProvider(@"c:/medias"),
    RequestPath = "/medias"
});

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.UseSwaggerUI(
        options =>
        {
            options.SwaggerEndpoint("../openapi/v1.json", "version 1");
        });
}

app.UseRouting();
// Enable CORS Feature
app.UseCors("CorsPolicy");

app.UseAuthorization();
app.MapHub<DownloadHub>("/downloadHub");
app.MapControllers();

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

app.Run();

Test Result

发布评论

评论列表(0)

  1. 暂无评论