Angular 5与MVC5中SignalR Hub 2连接失败求助
Hey, let's break down why you're hitting that JSON parsing error and fix it step by step!
The Root Cause
Your setup has a critical version mismatch:
- Backend: You're using the classic ASP.NET SignalR (
Microsoft.AspNet.SignalR), which is built for .NET Framework and uses an older protocol. - Frontend: You're using the ASP.NET Core SignalR client (
@aspnet/signalr-client), which is designed for the newer, incompatible ASP.NET Core SignalR implementation.
These two versions don't speak the same language, which causes the JSON parsing failure when trying to establish a connection.
Step-by-Step Fix
1. Update the Backend to ASP.NET Core SignalR
First, let's migrate your hub to the modern ASP.NET Core version (this is the recommended path for better compatibility and support):
a. Replace NuGet Packages
Uninstall Microsoft.AspNet.SignalR and install Microsoft.AspNetCore.SignalR.
b. Rewrite the Hub Class
using Microsoft.AspNetCore.SignalR; using System; namespace clockHub { public class ClockHub : Hub { public void GetRealTime() { // Use SendAsync instead of direct method calls (Core SignalR requirement) Clients.Caller.SendAsync("setRealTime", DateTime.Now.ToString("h:mm:ss tt")); } } }
c. Configure SignalR in Startup.cs
Add SignalR and CORS (critical if your Angular app runs on a different port) to your startup configuration:
public void ConfigureServices(IServiceCollection services) { // Configure CORS to allow your Angular app services.AddCors(options => { options.AddPolicy("SignalRCorsPolicy", builder => builder.WithOrigins("http://localhost:4200") // Replace with your Angular URL .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.AddSignalR(); // Other service configurations... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // CORS must be registered before SignalR app.UseCors("SignalRCorsPolicy"); app.UseRouting(); app.UseEndpoints(endpoints => { // Map the hub to your desired route endpoints.MapHub<ClockHub>("/clockHub"); // Other endpoint mappings... }); }
2. Fix the Frontend Angular Code
Update your client to use the correct ASP.NET Core SignalR package and syntax:
a. Update NPM Packages
Uninstall the old client package and install the official modern one:
npm uninstall @aspnet/signalr-client npm install @microsoft/signalr
b. Rewrite the Component Code
import { Component, OnInit } from '@angular/core'; import { HubConnectionBuilder, HubConnection } from '@microsoft/signalr'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; private _hubConnection: HubConnection; nick = ''; message = ''; messages: string[] = []; public getRealTime(): void { this._hubConnection .invoke('GetRealTime') // Match the exact method name (Core SignalR is case-sensitive) .catch(err => console.error(err)); } ngOnInit() { // Use HubConnectionBuilder instead of direct HubConnection instantiation this._hubConnection = new HubConnectionBuilder() .withUrl('/clockHub') .build(); this._hubConnection.start() .then(() => console.log('Connection started!')) .catch(err => console.log('Error while establishing connection :(', err)); this._hubConnection.on('setRealTime', (time: string) => { alert(time); }); } }
Key Notes to Remember
- Case Sensitivity: ASP.NET Core SignalR is case-sensitive, so ensure your frontend
invokemethod names match the backend exactly. - CORS Configuration: Always include CORS with
AllowCredentials()if your Angular app runs on a different origin than the backend. - Package Names: The official ASP.NET Core SignalR client is now
@microsoft/signalr(the old@aspnet/signalr-clientis deprecated).
内容的提问来源于stack exchange,提问作者behruz

