我无法连接到在Windows 7下运行的ASP.NET Core 2.0.3应用程序中的SignalR Hub。 我使用NuGet的SignalR 1.0.0-alpha1-final作为服务器,将signalr-client-1.0.0-alpha2-final.min.js作为JavaScript客户端使用。
这是我的中心:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace MyProject
{
public class MyHub: Hub
{
public override async Task OnConnectedAsync()
{
await Clients.All.InvokeAsync("Send", $"{Context.ConnectionId} joined");
}
public Task Send(string message)
{
return Clients.All.InvokeAsync("Send", $"{Context.ConnectionId}: {message}");
}
}
}
在startup.cs中配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseHangfireDashboard();
app.UseHangfireServer();
app.UseSignalR(routes =>
{
routes.MapHub<MyHub>("hubs");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
并在测试页面中:
let transportType = signalR.TransportType[getParameterByName('transport')] || signalR.TransportType.WebSockets;
let http = new signalR.HttpConnection(`http://${document.location.host}/hubs`, { transport: transportType });
var connection = new signalR.HubConnection(http);
但是当执行此代码时,我从服务器收到错误204。
根据@Gabriel Luci的答案,这里是工作代码:
let transportType = signalR.TransportType.LongPolling;
let http = new signalR.HttpConnection(`http://${document.location.host}/hubs`, { transport: transportType });
let connection = new signalR.HubConnection(http);
connection.start();
connection.on('Send', (message) => {
console.log(message);
});
...
connection.invoke('Echo', "Hello ");
答案 0 :(得分:3)
GitHub提出了一个问题:https://github.com/aspnet/SignalR/issues/1028
显然,WebSockets在IIS和IIS Express中不起作用。你需要使用长轮询。该问题中有一小段示例代码:
let connection = new HubConnection("someurl", { transport: signalR.TransportType.LongPolling });
connection.start().then(() => {});
答案 1 :(得分:1)
就我而言,我必须删除允许的任何来源并将其替换为WithOrigins和AllowCredentials
options.AddPolicy("policy",
builder =>
{
builder.WithOrigins("http://localhost:8081");
builder.AllowAnyMethod();
builder.AllowAnyHeader();
builder.AllowCredentials();
});