使用 IP 地址从 C# HttpClient 向同一台机器发出 HTTP 请求

Make HTTP Request from C# HttpClient to Same Machine using IP Address

基本上,我需要能够在我所在的同一台机器上向网站发出 HTTP 请求,而无需修改主机文件以创建指向域名的指针。

例如

我是 运行 一个网站上的代码,比方说 www.bobsoft.com 在服务器上。

我需要向同一台服务器上的 www.tedsoft.com 发出 HTTP 请求。

如何在不修改主机文件的情况下使用 C# HttpClient 进行调用? 考虑到网站是通过 IIS 中的绑定路由的。我确实知道我要提前使用的域,我只需要将它全部放在代码内部而不更改服务器。

谢谢!

基于 http Host header 路由相同端口但不同主机名的 IIS 绑定。这里最好的解决方案实际上是配置本地 DNS,这样对 www.tedsoft.com 的请求就不会离开机器。也就是说,如果这些类型的配置不是一个选项,您可以轻松地将主机 header 设置为 HttpRequestMessage.

的一部分

我在 IIS 上配置了 2 个测试站点。

  • 默认网站 - returns 文本 "test1"
  • 默认网站 2 - returns 文本 "test2"

以下代码使用 http://127.0.0.1http://localhost 也适用)并根据 IIS 绑定适当地设置主机 header 以获得您要查找的结果。

class Program
{
    static HttpClient httpClient = new HttpClient();

    static void Main(string[] args)
    {
        string test1 = GetContentFromHost("test1"); // gets content from Default Web Site - "test1"
        string test2 = GetContentFromHost("test2"); // gets content from Default Web Site 2 - "test2"
    }

    static string GetContentFromHost(string host)
    {
        HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, "http://127.0.0.1");
        msg.Headers.Add("Host", host);

        return httpClient.SendAsync(msg).Result.Content.ReadAsStringAsync().Result;
    }
}