我有一个 Asp.net core 的项目,我完成了它 现在我想给它添加 SignalR
我尝试将 signalR 添加到我的 asp.net 核心项目 但我有一个错误 它是“需要连接 ID” 我觉得我的错误在启动文件中
我的 Hub 类和我的 Controller 在聊天区(一个叫做聊天的区域)
这是我的启动文件:
using CoreLayer.Services.Chats;
using CoreLayer.Services.Chats.ChatGroups;
using CoreLayer.Services.Users.UserGroups;
using Echat.Hubs;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SendEmail;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using TopCoderZ.Core.Service;
using TopCoderZ.Core.Service.Interface;
using TopCoderZ.Core.Services;
using TopCoderZ.Core.Services.Interfaces;
using TopCoderZ.DataLayer.Context;
using TopLearn.Core.Services;
namespace FarsLearn.Web
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public string CookieAuthenticateSchemeDefaults { get; private set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var environment = services.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
services.AddDataProtection()
.SetApplicationName($"my-app-{environment.EnvironmentName}")
.PersistKeysToFileSystem(new DirectoryInfo($@"{environment.ContentRootPath}\keys"));
//services.AddMvc();
services.AddMvc(options => options.EnableEndpointRouting = false);
services.AddRazorPages();
//services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = 6000000; });
#region Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
options.ExpireTimeSpan = TimeSpan.FromMinutes(43200);
});
#endregion
#region DbContext
services.AddDbContext<TopCoderZContext>(p =>
{
p.UseSqlServer(Configuration.GetConnectionString("TopCoderZConnection"));
});
#endregion
#region IoC
services.AddTransient<IUserService, UserService>();
services.AddTransient<IViewRenderService, RenderViewToString>();
services.AddTransient<IPermissionService, PermissionService>();
services.AddTransient<ICourseService, CourseService>();
services.AddTransient<IOrderService, OrderService>();
services.AddTransient<IPostService, PostService>();
services.AddTransient<IForumService, ForumService>();
services.AddScoped<IChatService, ChatService>();
services.AddScoped<IChatGroupService, ChatGroupService>();
services.AddScoped<IUserGroupService, UserGroupService>();
#endregion
**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)
{
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
{
context.Response.Redirect("/Home/Error404");
}
});
app.Use(async (context, next) =>
{
if (context.Request.Path.Value.ToString().ToLower().StartsWith("/coursefilesonline"))
{
var callingUrl = context.Request.Headers["Referer"].ToString();
if (callingUrl != "" && (callingUrl.StartsWith("https://farslearn.com/") || callingUrl.StartsWith("http://farslearn.com/")))
{
await next.Invoke();
}
else
{
context.Response.Redirect("/Login");
}
}
else
{
await next.Invoke();
}
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseRouting();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
//app.UseMvc(routes =>
//{
// routes.MapRoute(
// name: "areas",
// template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
// );
// routes.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
//}); app.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyAreas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapControllerRoute(
name: "Default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapRazorPages();
**endpoints.MapHub<ChatHub>("/chat");**
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("FarsLearn || XXX Big Error");
});
}
}
}
我有一个错误
它是“需要连接ID” 我应该怎么办? 请帮助我
最佳答案
礼拜堂
在配置服务:
// SignalR step 1
services.AddSignalR();
// SignalR step 3
services.AddCors(options =>
{
options.AddPolicy("SignalRClientPolicy", policy =>
{
policy.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:3000", "https://www.me.com")
.AllowCredentials();
});
});
在配置时:
// SignalR step 4
app.UseCors("SignalRClientPolicy");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// SignalR setp 2
endpoints.MapHub<MainHub>("/MainHubEndpoint_rE4Tt3");
});
关于c# - asp.net core 中所需的 signalR 连接 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71692993/