代码之家  ›  专栏  ›  技术社区  ›  David C

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

  •  1
  • David C  · 技术社区  · 6 年前

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

    例如。

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

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

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

    谢谢!

    1 回复  |  直到 6 年前
        1
  •  1
  •   Neil    6 年前

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

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

    • 默认网站-返回文本“test1”
    • 默认网站2-返回文本“test2”

    IIS Website Configurations

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

    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;
        }
    }