WPF SignalR 服务器返回 HTTP 400 错误请求(主机地址无效)

Jag*_*SWE 6 c# wpf signalr signalr.client

我正在尝试设置一个 SignalR 集线器,以便能够通过网络将通知推送到一堆 WPF 客户端。我尝试遵循基本指南和教程,并创建了一个 WPF SignalR 服务器(仅用于测试目的)。它已放在我局域网中的服务器上,它的外观如下:

启动文件

class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HubConfiguration hc = new HubConfiguration();
        hc.EnableDetailedErrors = true;

        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR(hc);
    }
}
Run Code Online (Sandbox Code Playgroud)

主窗口.xaml.cs

public IDisposable SignalR { get; set; }
const string ServerURI = "http://localhost:8554";

private void StartServer()
{
    try
    {
        SignalR = WebApp.Start(ServerURI);
    }
    catch (TargetInvocationException)
    {
        WriteToConsole("A server is already running at " + ServerURI);
        return;
    }
    this.Dispatcher.Invoke(() => btnStopHub.IsEnabled = true);
}
Run Code Online (Sandbox Code Playgroud)

临时集线器

public class AdHocHub : Hub
{
    public void Send(string data)
    {
        Clients.All.notifyData(data);
    }

    public override Task OnConnected()
    {
        Application.Current.Dispatcher.Invoke(() => 
            ((MainWindow)Application.Current.MainWindow).WriteToConsole("Client connected: " + Context.ConnectionId));
        return base.OnConnected();
    }

    public Task OnDisconnected()
    {
        Application.Current.Dispatcher.Invoke(() =>
            ((MainWindow)Application.Current.MainWindow).WriteToConsole("Client disconnected: " + Context.ConnectionId));

        return base.OnDisconnected(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

服务器启动得很好。但是,当我尝试将客户端连接到它时,它拒绝给我一个400-Bad Request。如果我尝试导航到http://192.nnn.nnn.nnn/signalr所有我得到的是Bad Request - Invalid Hostname。如果我在同一台机器上运行服务器和客户端,一切都会正常工作。我在这里做错了什么?

客户端调用设置如下:

private async void ConnectAsync()
{
    Connection = new HubConnection(ServerURI);
    HubProxy = Connection.CreateHubProxy("AdHocHub");
    HubProxy.On<string>("notifyData", (notifyData) => this.Dispatcher.Invoke(() => txtEvents.AppendText(notifyData.ToString())));

    try
    {
        await Connection.Start();
    }
    catch (HttpRequestException ex)
    {
        MessageBox.Show(ex.ToString());
        lblStatus.Content = "Unable to connect to server: Start server before connecting clients.";
        return;
    }
    txtEvents.AppendText("Connected to server and listening...");
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试将服务器中的 URI 从主机名更改为它的 IP,但后来我只得到了一个TargetInvocationException,所以这无济于事。

如前所述,这整个设置似乎很好地工作,只要在同一台机器上的客户端和服务器的运行,但没有一次我动它,即使我已经设置了CorsOptionsAllowAll

Mat*_*t J 3

(将我自己的评论转换为答案,因为在大多数情况下它似乎是答案)

ServerURI将服务器从更改localhosthttp://+:8554,否则它将仅侦听 localhost。它在同一台机器上工作,因为它是本地主机。

但是一旦你将其更改为这个新方案,在调试时,你将需要 Visual Studio 在管理模式下运行,否则TargetInvocationException如果 UAC 打开,将会抛出异常。