Asp.Net Core 3 SignalR客户端连接远程Hub遇CORS错误求助
Let's break down the issues causing your CORS error and fix them step by step:
1. Trailing Slash in CORS Origin
Your CORS policy specifies http://localhost:10843/ (with a trailing slash), but browsers send the origin header without the trailing slash (http://localhost:10843). This mismatch causes the origin to be rejected.
Fix: Remove the trailing slash from your origin URL:
services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder .AllowAnyMethod() .AllowAnyHeader() .WithOrigins("http://localhost:10843") // No trailing slash here .AllowCredentials(); }));
2. Missing UseCors Middleware in Pipeline
You've defined a CORS policy, but you haven't applied it to your request pipeline. Middleware order matters—UseCors must come after UseRouting and before UseEndpoints.
Fix: Update your Configure method:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... other middleware like UseStaticFiles, UseAuthentication etc. app.UseRouting(); // Apply the CORS policy here app.UseCors("CorsPolicy"); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapHub<MyHub>("/signalr"); // Fix Hub class name mismatch here too! }); }
3. Hub Class Name Mismatch
You're mapping AsteriskHub to the /signalr endpoint, but your actual hub class is named MyHub. This mismatch will cause the server to fail routing the request, which can manifest as a CORS error (since the error response won't include the required CORS headers).
Fix: Ensure the mapped hub matches your actual class:
endpoints.MapHub<MyHub>("/signalr");
4. Mismatched SignalR Package Versions
You're using ASP.NET Core 3.1 but have installed SignalR packages version 1.1.0 (which targets ASP.NET Core 2.x). Version mismatches can break the negotiation process, leading to unexpected CORS errors.
Fix: Install the SignalR package matching your ASP.NET Core 3.1 version. For example, if you're on 3.1.32, run this in the Package Manager Console:
Install-Package Microsoft.AspNetCore.SignalR -Version 3.1.32
After applying all these fixes, restart both your server and client applications. The negotiation request should now pass the CORS check, and your SignalR connection should start successfully.
内容的提问来源于stack exchange,提问作者Mehdi

