我正在使用Razor组件Blazor服务器端ASP.NET Core项目。我有一个控制器,当收到新消息时,我从外部服务获取HTTP Post。我希望我的剃须刀组件在消息到达时立即显示它们。我希望多个剃刀组件能够注册到该事件
是否有一种方法可以从剃须刀组件注册到控制器内部的事件?还是应该使用其他方法,例如Xamarin Message Center?
控制器:
public class LoRaServerController : ControllerBase
{
public event EventHandler<SensorData>? OnNewSensorData;
// POST: api/LoRaServer
[HttpPost]
public async void PostUplink()
{
if (OnNewSensorData != null)
{
var uplink = await DeserializeBody<Uplink>(Request.Body);
if (uplink != null)
OnNewSensorData(this, new SensorData(uplink));
}
}
private async Task<T?> DeserializeBody<T>(Stream body) where T : class
{
//Json deserialization...
}
}
剃刀组件:
@attribute [Authorize(Roles = "Administrator")]
@page "/lora-debug"
@using Xxx.Controller
@using Xxx.Services.Entities
@inject LoRaServerController _ctrl; //this doesn't work as controllers are no services...
@implements IDisposable;
<h3>Sensor Server Debug</h3>
<table class="table">
<thead>
<tr>
<th>Time</th>
<th>EUI</th>
<th>Uptime</th>
<th>Voltage</th>
</tr>
</thead>
<tbody>
@foreach (var msg in sensorData)
{
<tr>
<td>@msg.Timestamp</td>
<td>@msg.DeviceEUI</td>
<td>@msg.Uptime</td>
<td>@msg.Voltage</td>
</tr>
}
</tbody>
</table>
@code {
private List<SensorData> sensorData = new List<SensorData>();
protected override void OnInitialized()
{
_ctrl.OnNewSensorData += Instance_OnNewSensorData;
}
public void Dispose()
{
_ctrl.OnNewSensorData -= Instance_OnNewSensorData;
}
private void Instance_OnNewSensorData(object? sender, SensorData e)
{
sensorData.Add(e);
InvokeAsync(() => this.StateHasChanged());
}
}