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();
});

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

相关推荐
神奇的程序员2 小时前
从已损坏的备份中拯救数据
运维·后端·前端工程化
oden3 小时前
AI服务商切换太麻烦?一个AI Gateway搞定监控、缓存和故障转移(成本降40%)
后端·openai·api
李慕婉学姐4 小时前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
m0_740043734 小时前
SpringBoot05-配置文件-热加载/日志框架slf4j/接口文档工具Swagger/Knife4j
java·spring boot·后端·log4j
招风的黑耳5 小时前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
Miss_Chenzr5 小时前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
期待のcode5 小时前
Springboot核心构建插件
java·spring boot·后端
2501_921649495 小时前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融
serendipity_hky6 小时前
【SpringCloud | 第5篇】Seata分布式事务
分布式·后端·spring·spring cloud·seata·openfeign
五阿哥永琪6 小时前
Spring Boot 中自定义线程池的正确使用姿势:定义、注入与最佳实践
spring boot·后端·python