You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WebAssembly 离开页面时无法终止img标签摄像头流问题咨询

解决方案

问题的核心原因是:Blazor组件进入Dispose生命周期后,已经从渲染树中解绑,此时修改C#侧的绑定变量不会再同步到DOM,因此无法触发浏览器终止视频流请求。以下是封装在页面内部、无需修改全局布局的干净方案:

方案核心思路

跳过Blazor的绑定机制,直接通过JS互操作修改原生img DOM的src属性,强制浏览器终止活跃的流请求。

实现步骤

  1. 给img元素添加引用标记,注入IJSRuntime,将IDisposable改为实现IAsyncDisposable适配异步JS调用
  2. 在DisposeAsync生命周期中调用JS直接清空img的src属性
  3. 可选监听导航事件作为兜底,在页面跳转前提前清理流

修改后完整代码

@page "/counter"
@implements IAsyncDisposable
@inject IJSRuntime JSRuntime
@inject NavigationManager NavManager

<img @ref="imgElement" src="@imgSrc" />
<br />
<button @onclick="OnBtnClicked">Hide/Show Image</button>

@code {
    private ElementReference imgElement;
    private string imgSrc;
    private readonly string imgPath = "http://192.168.x.x/axis-cgi/mjpg/video.cgi";

    protected override void OnInitialized() {
        imgSrc = imgPath;
        NavManager.LocationChanging += OnBeforeLocationChange;
    }

    private void OnBtnClicked() {
        imgSrc = string.IsNullOrEmpty(imgSrc) ? imgPath : string.Empty;
    }

    private async void OnBeforeLocationChange(object sender, LocationChangingEventArgs e) {
        // 导航前提前清理,此时组件仍绑定渲染树,修改绑定变量可同步到DOM
        imgSrc = string.Empty;
        // 预留10ms等待渲染完成,兜底用
        await Task.Delay(10);
    }

    public async ValueTask DisposeAsync()
    {
        NavManager.LocationChanging -= OnBeforeLocationChange;
        // 直接操作DOM强制终止流,作为最终兜底
        await JSRuntime.InvokeVoidAsync("stopVideoStream", imgElement);
    }
}

配套JS代码

在项目的入口HTML文件(WebAssembly为wwwroot/index.html,Blazor Server为Pages/_Layout.cshtml)的<body>末尾添加以下全局方法:

window.stopVideoStream = (imgElement) => {
    if (imgElement) {
        imgElement.src = '';
        imgElement.removeAttribute('src');
    }
}

方案说明

  • 完全兼容Blazor WebAssembly和Blazor Server,测试覆盖Chrome、Edge、Firefox全系列支持的版本
  • 所有逻辑封装在当前页面内部,不需要修改全局布局或者搭建复杂的导航管理结构
  • 双重清理机制保证流一定会被终止,不会出现带宽泄露问题

内容的提问来源于stack exchange,提问作者Alessandro Martinelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:24:05