Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以使用.NET Framework从指定的ip地址发送webrequest吗?_C#_.net_Ip Address_Webrequest - Fatal编程技术网

C# 我可以使用.NET Framework从指定的ip地址发送webrequest吗?

C# 我可以使用.NET Framework从指定的ip地址发送webrequest吗?,c#,.net,ip-address,webrequest,C#,.net,Ip Address,Webrequest,我有一个多ip地址的服务器。现在我需要使用http协议与多个服务器通信。每个服务器只接受来自我的服务器的指定ip地址的请求。但是在.NET中使用WebRequest(或HttpWebRequest)时,请求对象将自动选择ip地址。我找不到将请求与地址绑定的方法 有没有办法这样做?或者我必须自己实现一个webrequest类?不确定你是否读过这篇文章(?) 或 您需要使用ServicePoint.BindIPEndPointDelegate回调 在与httpwebrequest关联的套接字尝试

我有一个多ip地址的服务器。现在我需要使用http协议与多个服务器通信。每个服务器只接受来自我的服务器的指定ip地址的请求。但是在.NET中使用WebRequest(或HttpWebRequest)时,请求对象将自动选择ip地址。我找不到将请求与地址绑定的方法


有没有办法这样做?或者我必须自己实现一个webrequest类?

不确定你是否读过这篇文章(?)


您需要使用
ServicePoint.BindIPEndPointDelegate
回调

在与httpwebrequest关联的套接字尝试连接到远程端之前调用委托


如果要使用
WebClient
执行此操作,则需要对其进行子类化:

var webClient = new WebClient2(IPAddress.Parse("10.0.0.2"));
和子类:

public class WebClient2 : WebClient
{
    public WebClient2(IPAddress ipAddress) {
        _ipAddress = ipAddress;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = (WebRequest)base.GetWebRequest(address);

        ((HttpWebRequest)request).ServicePoint.BindIPEndPointDelegate += (servicePoint, remoteEndPoint, retryCount) => {

            return new IPEndPoint(_ipAddress, 0);
        };

        return request;
    }
}

(感谢@Samuel提供所有重要的ServicePoint.BindIPEndPointDelegate部分)

太棒了。问题就这么简单地解决了!谢谢,山姆。我不建议将端口设置为5000。如果在此端口上使用多个实例发出请求,则可能会导致超时。相反,我会将端口设置为0,并让tcp层处理连接,无论如何都会通过端口80。它在.NET Framework上运行良好,但在.NET Core上不工作,我不知道为什么。
public class WebClient2 : WebClient
{
    public WebClient2(IPAddress ipAddress) {
        _ipAddress = ipAddress;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = (WebRequest)base.GetWebRequest(address);

        ((HttpWebRequest)request).ServicePoint.BindIPEndPointDelegate += (servicePoint, remoteEndPoint, retryCount) => {

            return new IPEndPoint(_ipAddress, 0);
        };

        return request;
    }
}