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

Blazor 8版本如何获取远程IP地址?原6/7版本方法失效

在Blazor 8中获取远程IP地址的方法

Blazor 8引入了多渲染模式架构,不同模式下获取远程IP的方式存在差异,以下分场景逐一说明:

1. 服务器端渲染(SSR)/静态渲染场景

在App.razor或其他SSR组件中,可通过IHttpContextAccessor获取远程IP:

  • 第一步,在Program.cs中注册服务:
builder.Services.AddHttpContextAccessor();
  • 第二步,在组件中注入并调用:
@inject IHttpContextAccessor HttpContextAccessor

@{
    var remoteIp = HttpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
}

<p>远程IP地址:@remoteIp</p>

2. 交互式服务器组件场景

交互式服务器组件运行在服务器端,同样适用上述IHttpContextAccessor方案,注册服务后直接注入使用即可,无需额外配置。

3. 交互式WebAssembly组件场景

WebAssembly组件运行在客户端浏览器,无法直接访问服务器端HttpContext,可通过两种方式获取:

  • 方式一:SSR传递参数
    在SSR根组件(如App.razor)中获取IP,再通过组件参数传递给WebAssembly组件:

    <!-- App.razor(SSR模式) -->
    @inject IHttpContextAccessor HttpContextAccessor
    @rendermode InteractiveWebAssembly
    
    <ClientComponent RemoteIp="@HttpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString()" />
    

    客户端组件接收参数:

    <!-- ClientComponent.razor -->
    [Parameter]
    public string? RemoteIp { get; set; }
    
    <p>远程IP地址:@RemoteIp</p>
    
  • 方式二:API端点获取
    先在服务器端创建API接口返回IP:

    [ApiController]
    [Route("api/ip")]
    public class IpController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
            return Ok(ip);
        }
    }
    

    再在WebAssembly组件中调用该接口:

    @inject HttpClient Http
    
    @code {
        private string? remoteIp;
    
        protected override async Task OnInitializedAsync()
        {
            remoteIp = await Http.GetStringAsync("/api/ip");
        }
    }
    
    <p>远程IP地址:@remoteIp</p>
    

注意事项

若应用部署在反向代理(如Nginx、IIS)之后,需配置代理传递真实客户端IP,并在ASP.NET Core中信任代理:

// Program.cs
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    // 添加代理服务器IP到信任列表
    options.KnownProxies.Add(IPAddress.Parse("代理服务器IP"));
});

// 需在app.UseRouting()之前调用
app.UseForwardedHeaders();

内容的提问来源于stack exchange,提问作者David Thielen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:32:35