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

如何在IHttpHandler中获取Web请求对应的客户端远程端口

实现方案

.NET Framework 环境(对应你当前使用的IHttpHandler场景)

你所用的传统ASP.NET Framework中HttpRequest类未直接暴露UserHostPort属性,可通过以下两种方式获取客户端远程端口:

方式1:通过HttpWorkerRequest获取

public class EndpointReflectionHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string address = context.Request.UserHostAddress;
        // 从上下文获取底层WorkerRequest对象
        IServiceProvider provider = (IServiceProvider)context;
        HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
        int port = int.Parse(workerRequest.GetRemotePort());
        
        context.Response.ContentType = "text/plain";
        context.Response.Write($"{address}:{port}");
    }

    public bool IsReusable => true;
}

方式2:读取服务器变量

直接读取IIS注入的服务器变量直接获取:

int port = int.Parse(context.Request.ServerVariables["REMOTE_PORT"]);

ASP.NET Core 环境

如果是ASP.NET Core环境,框架已直接封装了对应属性:

public async Task InvokeAsync(HttpContext context)
{
    string address = context.Connection.RemoteIpAddress?.ToString();
    int port = context.Connection.RemotePort;
    
    context.Response.ContentType = "text/plain";
    await context.Response.WriteAsync($"{address}:{port}");
}

场景适配说明

  • 你的业务属于典型的P2P打洞场景,需要额外注意两点:
    • 客户端发起查询请求的套接字必须和后续用于监听、打洞的套接字是同一个,否则NAT设备分配的公网端口映射会发生变化,导致拿到的端口不可用
    • 如果服务端前面部署了反向代理、CDN等中间服务,需要在代理层配置将客户端真实IP和端口通过请求头透传,服务端读取X-Forwarded-For和X-Forwarded-Port头获取真实信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 17:54:01