我有一个 C# 后端应用程序和一个 Flutter 前端。在我的后端,我有一个 SignalR 服务,我想在我的 Flutter 应用程序中使用它。我的后端设置:
public class DangerReportHub : Hub
{
public async Task SendDangerReport(object message)
{
// Broadcast the danger report to all connected clients
await Clients.All.SendAsync("ReceiveDangerReport", message);
}
}
然后我有cors政策:
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true);
}));
然后注册集线器:
app.UseEndpoints(x =>
{
x.MapControllers();
x.MapHub<DangerReportHub>("/dangerReportHub");
});
在我的 Web api 调用中,我有以下 post 方法:
[HttpPost]
public async Task<IActionResult> ReportDanger([FromBody] DangerPostDTO dangerPostDTO)
{
var danger = await _dangerService.ReportDanger(dangerPostDTO.dangerId, dangerPostDTO.userId, dangerPostDTO.Location);
if (danger.Data)
{
var dangerSignalR = new DangerSignalRDTO
{
DangerId = dangerPostDTO.dangerId,
TimeReported = DateTime.Now.ToUniversalTime(),
ReportedBy = dangerPostDTO.userId,
Location = dangerPostDTO.Location
};
await _hubContext.Clients.All.SendAsync("ReceiveDangerReport", dangerSignalR);
return Ok();
}
return BadRequest(danger.ErrorMessages);
}
然后在我的 flutter 应用程序中,我尝试使用 signalr_netcore 包来使用这个 signalr 核心。这是我的设置:
Future<void> _initHubConnection() async {
// The location of the SignalR Server.
const serverUrl = "http://*.*.*.*/dangerReportHub"; // IP is hidden for this question only
// Creates the connection by using the HubConnectionBuilder.
final hubConnection = HubConnectionBuilder()
.withUrl(serverUrl)
.withAutomaticReconnect()
.build();
hubConnection.onclose(({Exception? error}) => print(error.toString()));
await hubConnection.start();
hubConnection.on("ReceiveDangerReport", _handleAClientProvidedFunction);
}
void _handleAClientProvidedFunction(dynamic? parameters) {
debugPrint(parameters.toString());
return null;
}
所以奇怪的是,当我从信号器测试客户端执行测试调用时https://gourav-d.github.io/SignalR-Web-Client/dist/并且我直接从集线器调用SendDangerReport , 有用。但是当我调用 WEB API 时,Flutter 客户端没有收到消息。 可能出了什么问题?
问题出在 Location 属性上。这是一个尚未开始序列化的复杂属性。