我目前正在使用React和SignalR。我正在使用.Net Core 2.1和Microsoft.AspNetCore.App软件包来获取最新的SignalR。我也已经安装了@ aspnet / signalr,并且不断收到404错误,因为它仍在尝试转到/ negotiate端点,我知道它不再使用了。我确认我在所有包装上都是最新的。关于我应该去哪里的任何指示?
const hubConnection = new HubConnectionBuilder().withUrl('http://localhost:3000/ChatHub').build();
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(o => o.AddPolicy("CorsPolicy", builder =>
//{
// builder
// .AllowAnyMethod()
// .AllowAnyHeader()
// .WithOrigins("http://localhost:3000");
//}));
services.AddSignalR();
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// 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.UseCors("CorsPolicy");
app.UseFileServer();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/ChatHub");
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
//app.UseMvc(routes =>
//{
// routes.MapRoute(
// name: "default",
// template: "{controller}/{action=Index}/{id?}");
//});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
答案 0 :(得分:3)
我不断收到404错误,因为它仍在尝试转到/ negotiate端点,我知道它不再使用
ASP.NET Core SignalR肯定仍使用/negotiate
端点。在预览中,我们改用了OPTIONS
请求,但这引起了很多问题,因此我们回到了/negotiate
端点。
您似乎正在使用“开发服务器”(启动中的spa.UseReactDevelopmentServer
)。通常,这意味着开发服务器正在从另一台服务器提供HTML / JS内容,而不是ASP.NET Core应用在其上运行(而不只是ASP.NET Core提供的静态文件)应用)。如果是这种情况,则在连接时需要使用完整的URL引用ASP.NET Core服务器。
这是因为开发服务器正在http://localhost:X
处提供HTML / JS内容,而ASP.NET Core服务器正在http://localhost:Y
处运行。因此,当您将/ChatHub
用作URL时,浏览器会将其解释为http://localhost:X/ChatHub
,因此您无需运行ASP.NET Core应用程序(使用SignalR服务器),而是运行dev服务器,该服务器具有该URL没有内容,并产生404。