【问题标题】:Connection to SignalR Hub fails with Negotiate 404 (not found)与 SignalR 集线器的连接失败并出现协商 404(未找到)
【发布时间】:2019-03-28 17:05:12
【问题描述】:

我已经研究这个问题 3 天了,但找不到解决方案。我使用以下代码创建了一个 SignalR Hub:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace Messenger.Hubs
{
    public class MessengerHub : Hub 
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

够简单,启动代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Messenger.Hubs;

namespace Messenger
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSignalR();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("c:/myapp/Messenger");
            });
            app.UseMvc();
        }
    }
}

我几乎从互联网上某个地方发布的解决方案中剪切并粘贴了代码,但我忘记了在哪里,而不是 stackoverflow。然后,我使用 Visual Studio 2017 (v15.9.10) 在 Xamarin (v4.12.3.81) 项目中创建了以下客户端。该代码是:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;

namespace SignalR.Client.Hubs
{
    public class SampleHub
    {
        // MessengerHub is a appliaction folder aliased as MessengerHub
        // the direct path on the machine is c:\mywebapp\messenger
        private const string _hubUrl = "http://example.com/MessengerHub";
        private readonly HubConnection _hubConnection;
        public event EventHandler<string> OnMessageReceived;

        public SampleHub()
        {
            var builder = new HubConnectionBuilder().WithUrl(_hubUrl);
            _hubConnection = builder.Build();
        }

        public async Task<bool> ConnectAsync()
        {
            try
            {
                await _hubConnection.StartAsync();
                _hubConnection.On("messageReceived", (string platform, string message) =>
                {
                if (OnMessageReceived != null)
                    {
                        OnMessageReceived(this, string.Format("{0}: {1}", platform, message));
                    }
                });
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                //Console.WriteLine($"Connection error: {ex.Message}");
                return false;
            }

            return true;
        }

        public async Task<int> GetNumberAsync(int number)
        {
            return await _hubConnection.InvokeAsync<int>("GetNumber", number);
        }

        public Task Send(string message)
        {
            return _hubConnection.SendAsync("Send", message);
        }
    }
}

活动中使用该客户端的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

using Android.Views.InputMethods;
using SignalR.Client.Hubs;


namespace MyXamarinApp
{
    [Activity(Label = "Messenger")]
    public class Messenger : Activity
    {
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.Messenger);

            RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
            try
            {
                var input = FindViewById<EditText>(Resource.Id.Input);
                var messages = FindViewById<ListView>(Resource.Id.Messages);

                var inputManager = (InputMethodManager)GetSystemService(InputMethodService);
                var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new List<string>());

                messages.Adapter = adapter;

                var hub = new SampleHub();


                await hub.ConnectAsync(); // <---- fails here

                input.EditorAction +=
                  delegate
                  {
                      inputManager.HideSoftInputFromWindow(input.WindowToken, HideSoftInputFlags.None);

                      if (string.IsNullOrEmpty(input.Text))
                          return;

                      hub.Send(input.Text);

                      input.Text = "";
                  };

                hub.OnMessageReceived +=
                  (sender, message) => RunOnUiThread(() =>
                    adapter.Add(message));
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
            }
        }
    }
}

集线器(我相信)在服务器上正常运行,我设置了登录,这就是日志中的内容:

Hosting environment: Production
Content root path: C:\mywebapp\Messenger
Application started. Press Ctrl+C to shut down.

尝试连接到集线器会产生以下错误:

{System.Net.Http.HttpRequestException: 404 (Not Found)

  at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode () [0x0002a] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0

  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<NegotiateAsync>d__44.MoveNext () [0x00226] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  --- at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<GetNegotiationResponseAsync>d__51.MoveNext () [0x00077] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<SelectAndStartTransport>d__43.MoveNext () [0x00169] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  ---
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<StartAsyncCore>d__40.MoveNext () [0x00118] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  --- at System.Threading.Tasks.ForceAsyncAwaiter.GetResult () [0x0000c] in <843c441fa9954906b53e3710152bebb9>:0

  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<StartAsync>d__39.MoveNext () [0x0008b] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  --- at Microsoft.AspNetCore.SignalR.Client.HttpConnectionFactory+<ConnectAsync>d__3.MoveNext () [0x0009d] in <d50de232736c4c8f910083ea0cb358a8>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at Microsoft.AspNetCore.SignalR.Client.HttpConnectionFactory+<ConnectAsync>d__3.MoveNext () [0x00142] in <d50de232736c4c8f910083ea0cb358a8>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at Microsoft.AspNetCore.SignalR.Client.HubConnection+<StartAsyncCore>d__47.MoveNext () [0x00130] in <f381011e9b214489bcb373743f31ed9d>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at System.Threading.Tasks.ForceAsyncAwaiter.GetResult () [0x0000c] in <f381011e9b214489bcb373743f31ed9d>:0

  at Microsoft.AspNetCore.SignalR.Client.HubConnection+<StartAsync>d__39.MoveNext () [0x00091] in <f381011e9b214489bcb373743f31ed9d>:0

--- End of stack trace from previous location where exception was thrown
  ---
  at SignalR.Client.Hubs.SampleHub+<ConnectAsync>d__6.MoveNext () [0x00037] in C:\Users\<username>\Documents\Visual Studio 2017\Projects\signalr_client\signalr_client\Resources\layout\Client.cs:28 }

这是我在站点的 IIS 日志中看到的内容。

"POST /MessengerHub/negotiate HTTP/1.1" 303 446
"GET /MessengerHub/negotiate HTTP/1.1" 404 1509

我不知道下一步该尝试什么。

【问题讨论】:

  • 您在服务器中有chatHub,但正在尝试在客户端使用MessengerHub。
  • 只是一个类名,改了...没什么区别,完全相同的问题。
  • 如果你有一个这样声明的集线器:public class ChatHub:Hub 那么你必须确保你的骆驼案例引用:routes.MapHub("/chatHub"); (这会起作用)。但是,这不起作用: routes.MapHub("/chathub"); routes.MapHub("/ChatHub"); 也不会不确定您在上面所做的更改,因为您没有显示更改。
  • 显然问题在于服务器以某种方式找不到信号器,我在 routes.MapHub 中放了什么并不重要,服务器正在寻找一个名为 negotiate 的文件夹在定义的路径上配置中不存在的 routes.MapHub。不知道它来自哪里或如何解决它。
  • 仅供参考 ...我从 docs.microsoft.com/en-us/aspnet/core/tutorials/… 复制了集线器代码,在 IIS Express 中运行,显然不是 IIS 8.5。

标签: c# asp.net-core xamarin.android visual-studio-2017 signalr


【解决方案1】:

我今天遇到了这个错误,在浪费了一些时间之后,我只是忘记了添加:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<FooHub>("/FooHub");
});

到我的 .NET 5 ASP.NET 应用程序中的 Startup.cs >> public void Configure(...)。

自从这篇文章最初发布以来,情况发生了一些变化(我确实看到了一些 Xamarin),但希望这能给将来的人一些指导。

【讨论】:

    【解决方案2】:

    SignalR NetCore 5,Blazor webassembly 项目在部署到 IIS 时遇到了同样的问题,在开发机器上的 localhost 中运行良好。

    解决方案是在集线器连接中使用完整的 url: 首先在 Startup.cs 中包含 hub 端点

     endpoints.MapHub<BroadcastHub>("/broadcastHub");
    

    然后在设置集线器连接时,改为

       hubConnection = new HubConnectionBuilder()
                  .WithUrl(navigationManager.ToAbsoluteUri("/broadcastHub")
                     .Build();
    

    使用完整的网址:

         hubConnection = new HubConnectionBuilder()
                .WithUrl("http://myserver.com/bcwa/broadcastHub")
                .Build();
    

    bcwa 是我的 IIS 部署文件夹

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 2017-03-11
      相关资源
      最近更新 更多