使用IP地址从C#HttpClient向同一台计算机发出HTTP请求 [英] Make HTTP Request from C# HttpClient to Same Machine using IP Address

查看:302
本文介绍了使用IP地址从C#HttpClient向同一台计算机发出HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如.

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

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

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

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

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

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.

谢谢!

推荐答案

基于http Host标头.最好的解决方案实际上是配置本地DNS,这样对www.tedsoft.com发出的请求就不会离开计算机.话虽这么说,如果不是这样的配置,则可以轻松地将主机标头设置为HttpRequestMessage的一部分.

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.

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

I have 2 test sites configured on IIS.

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

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

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

这篇关于使用IP地址从C#HttpClient向同一台计算机发出HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆