Asp.net Core SignalR 跨域设置(Furion)

前端VUE2.0/3.0

后端NET8.0/NET6.0

框架Furion

前端安装SignalR通信库,下面任意一条安装指令都可以,根据项目自行选择

c 复制代码
npm install @microsoft/signalr
yarn add @microsoft/signalr

前端使用

javascript 复制代码
<script>
import { HubConnectionBuilder } from '@microsoft/signalr';
const connection = new HubConnectionBuilder().withUrl('http://localhost:5000/chatHub').build();
connection.start()//启动连接
connection.on('需要订阅的主题', 消息处理方法(有1个参数))//订阅主题
</script>

后端使用

在Startup文件中注册服务

csharp 复制代码
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();//添加即时通信
        }

在Startup文件中设置服务

csharp 复制代码
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();
    app.UseCors("localhost:5000");

    app.UseCorsAccessor();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseInject(string.Empty);

    app.UseEndpoints(endpoints =>
    {
        //注册集线器
        endpoints.MapHub<ChatHub>("/chatHub").RequireCors(t=>t.SetIsOriginAllowed((host)=>true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
        endpoints.MapControllers();
    });
}

创建一个你自己的Hub类,我这里叫ChatHub

csharp 复制代码
    public class ChatHub : Hub
    {

    }

在其他服务中使用SignalR发布主题

csharp 复制代码
    public class OutService:IDynamicApiController,ITransient
    {
        private readonly IHubContext<ChatHub> _hubContext;

        public OutService(IHubContext<ChatHub> hubContext)
        {
            _hubContext = hubContext;
        }

        /// <summary>
        /// 测试发布主题
        /// </summary>
        /// <param name="user">主题</param>
        /// <param name="message">消息</param>
        /// <returns></returns>
        [HttpPost("send/log")]
        public async Task SendLog(string user,string message)
        {
            await _hubContext.Clients.All.SendAsync(user, message);
        }
    }

问题:前端通过SignalR连接后端时CORS报错(跨域)

解决方案

1.注册时配置跨域(注意顺序)

csharp 复制代码
app.UseRouting();
app.UseCors("localhost:5000");

2.设置MapHub跨域

csharp 复制代码
app.UseEndpoints(endpoints =>
{
    //注册集线器
    endpoints.MapHub<ChatHub>("/chatHub").RequireCors(t=>t.SetIsOriginAllowed((host)=>true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
    endpoints.MapControllers();
});

通过以上设置就能完美解决跨域问题

相关推荐
LucianaiB27 分钟前
【程序员副业指南】KwaiKAT AI制作小红薯📕卡片MCP
后端
IT_陈寒44 分钟前
Redis性能翻倍的5个冷门优化技巧,90%的开发者都不知道第3个!
前端·人工智能·后端
阿琦学代码1 小时前
Spring Cloud(微服务) 概述
后端·spring·spring cloud
GreatSQL2 小时前
GreatSQL CTE 查询报告临时表找不到问题解析
后端
用户68545375977692 小时前
🎛️ JVM调优秘籍:把你的Java程序调教成性能怪兽!
后端
Asthenia04122 小时前
一次空值查询的“陷阱”排查:为什么我的接口不返回数据了?
后端
回家路上绕了弯2 小时前
慢查询优化全攻略:从定位根源到落地见效的实战指南
后端·性能优化
长存祈月心2 小时前
Rust HashSet 与 BTreeSet深度剖析
开发语言·后端·rust
长存祈月心2 小时前
Rust BTreeMap 红黑树
开发语言·后端·rust
京东云开发者2 小时前
提供方耗时正常,调用方毛刺频频
后端