【发布时间】:2020-07-10 07:42:46
【问题描述】:
我创建了一个 .net core web api 项目并尝试使用 SignalR 并连接到 Angular 应用程序。
我在与 Angular 建立连接时遇到错误。
WebSocketTransport.js:85 WebSocket connection to 'wss://localhost:44363/api/message' failed: Error during
WebSocket handshake: Unexpected response code: 200
我的启动.cs
namespace SignalR_server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder
.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddSignalR();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<MessageHub>("/message");
});
}
}
}
和 MessageController.cs
public class MessageController : ControllerBase
{
private IHubContext<MessageHub> _myHub;
public MessageController(IHubContext<MessageHub> hub)
{
_myHub = hub;
}
[HttpGet]
public Message Get()
{
Message msg = new Message();
msg.Id = 1;
msg.Name = "name";
msg.Msg = "This is a test message";
_myHub.Clients.All.SendAsync("transfermessage", msg);
return msg;
}
在我的客户端连接中,我将 skipNegotiation 设为 true
public startConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://localhost:44363/api/message',{
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
我错过了什么?
【问题讨论】:
-
为什么是
/api/message?你的路径似乎是/message
标签: c# angular asp.net-core websocket signalr