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 https://github.com/d052057/YtSharp

Any input leads to solve this issue is very appreciated.

Thanks.

0

1 Answer 1

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.

enter image description here

  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

enter image description here

Sign up to request clarification or add additional context in comments.

8 Comments

I did add CORS to the program.cs. You are correct that is no error in the live env. Another issue is that the downloadStatus in component.ts (in constructor()) did receive info from server but the data did not show up or display on screen in html template. I did console.log the status and it shows that the status info change from time to times. Thanks.
code:constructor() { // Subscribe to progress updates from SignalR this.signalRService.progress$.subscribe(({ downloadId, status }) => { console.log("Progress$ DownloadID="+ downloadId+ " status="+ JSON.stringify(status)) if (downloadId === this.currentDownloadId) { this.downloadStatus = status; console.log("progress$:"+ JSON.stringify(status)); // Update UI with latest output
@D052057 The another issue is another story. I have checked it , it should be related to angular, not signalr.
@D052057 Since I am not an Angular expert, I think your second problem may be related to Angular's refresh mechanism or asynchronous operation, so I set a delay of 0.5s to make sure your code works.
@D052057 For questions related to Angular, you can re-post a thread and add the tag "angular" so that other members can see your latest updates.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.