简体   繁体   English

C# 使用 HttpWebRequest 通过代理调用 API

[英]C# call an API through proxy using HttpWebRequest

I want to make an API call (outside my organization domain) in my existing application, the network team has told me to set up a proxy config - only then it'd have the ability to go to the internet.我想在我现有的应用程序中进行 API 调用(在我的组织域之外),网络团队告诉我设置代理配置 - 只有这样它才能访问互联网。 Dev has the ability to go to the internet without referencing the proxy setup.开发人员可以在不参考代理设置的情况下访问互联网。

In my dev environment, it is working fine since the ports are open, how to configure a proxy for UAT environment so that it can hit the new target on the internet?在我的开发环境中,由于端口是开放的,它工作正常,如何为 UAT 环境配置代理,以便它可以在互联网上击中新目标? proxy IP is given by the network team for Non-prod: 12.XXX.XXX.0 Port 80代理 IP 由网络团队为非产品提供:12.XXX.XXX.0 端口 80

and also how to check:以及如何检查:

  • if the above proxy is alive?如果上面的代理还活着?
  • once it is configured how to check if the request is going through the proxy because I just have dev server access where all ports are open, how would I check if it is configured correctly so that once deployed on UAT it works fine?一旦配置了如何检查请求是否通过代理,因为我只有所有端口都打开的开发服务器访问权限,我将如何检查它是否配置正确,以便一旦部署在 UAT 上它就可以正常工作?

The HttpWebRequest has a proxy property: HttpWebRequest有一个代理属性:

var myWebRequest = (HttpWebRequest)WebRequest.Create("url");
myWebRequest.Proxy = new WebProxy("host", 80);

try 
{
    var response = myWebRequest.GetResponse();
    //...
} 
catch (WebException e)
{
    // handling issues
}

If a request fails, an exception will be thrown that you can handle in catch block.如果请求失败,则会抛出异常,您可以在catch块中处理该异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM