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

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

相关推荐
qq_2975746718 分钟前
【实战】POI 实现 Excel 多级表头导出(含合并单元格完整方案)
java·spring boot·后端·excel
郝学胜-神的一滴30 分钟前
超越Spring的Summer(一): PackageScanner 类实现原理详解
java·服务器·开发语言·后端·spring·软件构建
Tony Bai33 分钟前
“Go 2,请不要发生!”:如果 Go 变成了“缝合怪”,你还会爱它吗?
开发语言·后端·golang
Victor3561 小时前
Hibernate(91)如何在数据库回归测试中使用Hibernate?
后端
Victor3561 小时前
MongoDB(1)什么是MongoDB?
后端
Victor3567 小时前
https://editor.csdn.net/md/?articleId=139321571&spm=1011.2415.3001.9698
后端
Victor3567 小时前
Hibernate(89)如何在压力测试中使用Hibernate?
后端
灰子学技术9 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
Gogo81610 小时前
BigInt 与 Number 的爱恨情仇,为何大佬都劝你“能用 Number 就别用 BigInt”?
后端
fuquxiaoguang10 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析