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

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

相关推荐
大鸡腿同学13 小时前
身弱体质|你的 FM 该关了📻
后端
Csvn14 小时前
📊 SQL 入门 Day 18:索引原理
后端·sql
Csvn14 小时前
🐍 Day3 : Python 容器精讲 — list、dict、set、tuple 底层实现与高级操作
后端·python
用户9385156350714 小时前
ESLint 代码规范完全指南——从 AST 原理到 flat config 逐行解析
javascript·后端·代码规范
用户9385156350714 小时前
深入理解 Next.js:从 SPA 的 SEO 问题到约定式路由与 SSR 原理
前端·后端·全栈
码事漫谈16 小时前
Deepseek涨价了,前后对比,竟然差这么多
后端
东风破_17 小时前
大前端手里的 Next.js:从 #root 到 SEO,一份 HTML 的两种命运
前端·后端
IT_陈寒18 小时前
Vue的v-for不听话?我被这个Key的坑整懵了
前端·人工智能·后端
众人皆醒我独醉18 小时前
训练加速实战:Flash Attention、Gradient Checkpointing 与数据流水线
后端·面试·gpu
阿黎梨梨18 小时前
Next.js 全栈开发:从 SPA 的痛点到 SSR 的破局之道
前端·后端