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

末鹿安然 提交于 2019-12-11 12:56:45

问题


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.

For example.

I am running the code on one website, let's say www.bobsoft.com which is on a server.

I need to make an HTTP request to www.tedsoft.com which is on the same server.

How can I make a call using a C# HttpClient without modifying the host file? Take into account that the websites are routed by bindings in IIS. I do know the domain I am going to use ahead of time, I just have to make it all internal in the code without server changes.

Thanks!


回答1:


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


来源:https://stackoverflow.com/questions/51505931/make-http-request-from-c-sharp-httpclient-to-same-machine-using-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!