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

后端 未结 1 1539
南笙
南笙 2021-01-24 18:57

Basically, I need to be able to make an HTTP Request to a Website on the same machine I am on, without modifying the host file to create a pointer to the domain name.

Fo

相关标签:
1条回答
  • 2021-01-24 19:33

    IIS bindings on the same port but different hostnames are routed based on the http Host header. The best solution here is really to configure local DNS so requests made to www.tedsoft.com don't leave the machine. That being said, if these kinds of configuration aren't an option you can easily set the host header as a part of your HttpRequestMessage.

    I have 2 test sites configured on IIS.

    • Default Web Site - returns text "test1"
    • Default Web Site 2 - returns text "test2"

    The following code uses http://127.0.0.1 (http://localhost also works) and sets the host header appropriately based on the IIS bindings to get the result you're looking for.

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题