Angular连接到ASP.NET API SignalR Hub返回404 Not Found(Identity Server 3)。
创始人
2024-10-28 00:00:47
0

问题描述: 在Angular应用程序中,尝试连接到ASP.NET API的SignalR Hub时,返回404 Not Found错误。

解决方法:

  1. 确保在Angular应用程序中正确安装和配置了SignalR模块。可以使用以下命令安装SignalR模块:
npm install @aspnet/signalr
  1. 在Angular应用程序的app.module.ts文件中导入SignalR模块,并将其添加到NgModule的imports数组中:
import { SignalRModule } from '@aspnet/signalr';

@NgModule({
  imports: [
    SignalRModule.forRoot()
  ],
  ...
})
export class AppModule { }
  1. 在需要使用SignalR的组件中导入SignalR服务,并在构造函数中注入它:
import { SignalRService } from './signalr.service';

@Component({
  ...
})
export class MyComponent {
  constructor(private signalRService: SignalRService) { }
}
  1. 创建一个名为SignalRService的服务,并在其构造函数中初始化SignalR连接:
import { Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';

@Injectable({
  providedIn: 'root'
})
export class SignalRService {
  private hubConnection: HubConnection;

  constructor() {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl('http://your-api-url/signalr-hub') // 替换为你的API的SignalR Hub URL
      .build();

    this.hubConnection.start()
      .then(() => console.log('SignalR connection started'))
      .catch(err => console.log('Error while starting SignalR connection: ' + err));
  }
}

请确保将上述代码中的http://your-api-url/signalr-hub替换为你的API的SignalR Hub的URL。

  1. 确保在ASP.NET API项目中正确配置了SignalR Hub。在Startup.cs文件的ConfigureServices方法中添加以下代码:
services.AddSignalR();

Configure方法中添加以下代码:

app.UseSignalR(routes =>
{
    routes.MapHub("/signalr-hub"); // 替换为你的Hub类的名称
});

请确保将上述代码中的YourHubClass替换为你的Hub类的名称。

  1. 确保ASP.NET API项目中正确配置了Identity Server 3。请参考Identity Server 3的文档进行正确的配置。

  2. 确保API的SignalR Hub的URL在Identity Server 3的允许列表中。在Identity Server 3的配置文件中,添加以下代码:

public static IEnumerable GetClients()
{
    return new List
    {
        new Client
        {
            ...
            AllowedCorsOrigins = new List
            {
                "http://your-angular-app-url" // 替换为你的Angular应用程序的URL
            },
            ...
        }
    };
}

请确保将上述代码中的http://your-angular-app-url替换为你的Angular应用程序的URL。

  1. 重新启动Angular应用程序和ASP.NET API项目,然后尝试连接到SignalR Hub。

希望上述解决方法能帮助到你解决问题!

相关内容

热门资讯

透视烘培!aa poker辅助... 透视烘培!aa poker辅助,AApoker透视软件总是有工具,八分钟教程(有挂存在)aa pok...
透视总结!wpk辅助哪里买,w... 透视总结!wpk辅助哪里买,wpk控制牌是真的吗(透视)果然有技巧(哔哩哔哩)1、下载好透视辅助下载...
透视策略!德普之星辅助软件,德... 透视策略!德普之星辅助软件,德普之星工具切实存在有插件,第2分钟教程(有挂教学)德普之星辅助软件能透...
一直以来!aapoker透视插... 一直以来!aapoker透视插件,微信小程序微乐破解器2024,揭幕透视(新版有挂)-哔哩哔哩1、首...
透视好友!pokemmo手机脚... 透视好友!pokemmo手机脚本辅助器,微乐贵阳足鸡麻将开挂,科普透视(今日头条)-哔哩哔哩poke...
透视积累!德普之星透视辅助软件... 透视积累!德普之星透视辅助软件下载,德普之星私人局总是是有透视,第3分钟教程(确实有挂)1、玩家可以...
透视手段!wpk辅助哪里买,W... 透视手段!wpk辅助哪里买,WPK有透视一直真的是有工具,7分钟教程(有挂透视)1、玩家可以在wpk...
这一现象值得深思!xpoker... 这一现象值得深思!xpoker辅助器,微乐自建房辅助软件功能,总结脚本(有挂解惑)-哔哩哔哩xpok...
透视绝活!wepoker软件辅... 透视绝活!wepoker软件辅助程序,WePoKer透视果然真的是有工具,8分钟教程(有挂秘诀)1、...
今日!wepoker好友房开挂... 今日!wepoker好友房开挂,微乐春天扑克开挂辅助插件,开挂脚本(有挂存在)-哔哩哔哩1、上手简单...