当前位置: 首页 > news >正文

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

前端VUE2.0/3.0
后端NET8.0/NET6.0
框架Furion

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

npm install @microsoft/signalr
yarn add @microsoft/signalr

前端使用

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

后端使用

在Startup文件中注册服务

        public void ConfigureServices(IServiceCollection services){services.AddSignalR();//添加即时通信}

在Startup文件中设置服务

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

    public class ChatHub : Hub{}

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

    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.注册时配置跨域(注意顺序)

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

2.设置MapHub跨域

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

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


http://www.mrgr.cn/news/53780.html

相关文章:

  • 柯桥俄语学习,旅游俄语中的支付和交际常用语句
  • 【SpringBoot】16 文件上传(Thymeleaf + MySQL)
  • 可编辑PPT | 生产及质量BI应用场景方案
  • 【Spring MVC】创建项目和建立请求连接
  • 自动化检查网页的TDK,python+selenium自动化测试web的网页源代码中的title,Description,Keywords
  • 云原生介绍
  • 软件工程的学习之详细绪论
  • Excel中如何进行傅里叶变换(FT),几步完成
  • 【JAVA毕业设计】基于Vue和SpringBoot的时装购物系统
  • 高效监控系统:Nightingale本地化部署与远程访问指南
  • 【经管】比特币与以太坊历史价格数据集(2014.1-2024.5)
  • 【C#】WPF 依赖属性,PasswordBox中的Password属性绑定
  • Unity Apple Vision Pro 保姆级开发教程-准备阶段
  • 使用pyqt编写一个可控制的移动矩形
  • 【C语言】strtok、strerror函数
  • 智融SW6236 AACC 四口多协议移动电源 SOC
  • 大话设计模式解读07-模板方法
  • 2024 复健记
  • C++左值和右值
  • csdn(最新交流群)
  • 本机运行Nacos容器每次都要重新创建容器,该怎么办?
  • Mockito单元测试的坑
  • 【Canvas与艺术】八瓣点心包裹之一
  • 【工具变量】A股上市企业大数据应用(2001-2023年)-参考柏淑嫄实践
  • 数据结构_day3
  • 【北京迅为】《STM32MP157开发板嵌入式开发指南》- 第四十五章 注册字符类设备