RESTcall with Restsharp does not work (using a Proxy) - c#

I am trying to make a RESTcall in C# with Restsharp (V 106.6.10). When I am executing the code on my personal PC it works very well. But when I am executing the same code on another PC (for work), which is using a Proxy, it does not work anymore. I am getting the following error:
Anfragefehler: Error calling TestPut: Unable to connect to the remote server (0)
TestPut is the method which should call the API
To solve that I have written the following code in my app.config. This should declare the proxy:
<system.net>
<defaultProxy enabled="true">
<proxy bypassonlocal="True"
proxyaddress="http://[IP]:[Port]/"/>
</defaultProxy>
</system.net>
I also tried to assign the Proxy in the constructor of my APIclient with:
WebProxy myproxy = new WebProxy("[IP]", [Port]);
request.Proxy = myproxy;
I also logged the ProxyURL and this seems to be correct...
What could be the error? Do you need any additional information?
I am calling an endpoint from AWS and when I call this Endpoint in the Browser it works.
Thank you in advance
Lukas

Related

Why does console apps use proxy by default?

I am currently having some issues with class library that doesn't behave as its console app.
The purpose of the console app is to send messages to an azure queue, which it does without any problem, and can see in ressource monitor that it makes calls through our web proxy and to our azure queue. This is done by default, I haven't told it anyway that it should use this proxy.
The class library on the other hand, does the same thing, but does not use the proxy, and therefore not able to send its data.
Both projects are identical, in the way they make the call to send a message, but for some reason is the console app, which intention is only to send a message, and library which intention is the same, act differently - why does the console app try to use proxy, and how do i force the class library to forcefully use the proxy?
conclusion:
How do i force a Microsoft.ServiceBus.Messaging.QueueClient.send
to use a proxy and not port 443
Per my knowledge, It is impossible to set the proxy while using service bus client.
The only connection options for Service Bus client are as following:
HTTP - port 80
HTTPS - port 443
TCP - 9350 to 9354
For more information we can refer to:
ConnectivityMode Enum
In your class library, please set the connectivity mode to Http as below code and try again:
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;
Similar thread as yours: Azure Service Bus working behind proxy
To answer my own question.
I resolved the issue by creating a proxy.config , and add it to my app.config.
proxy.config format:
<?xml version="1.0"?>
<defaultProxy enabled="true">
<proxy autoDetect="False" proxyaddress="http://<proxyaddress>:<port>" />
<bypasslist>
<add address="localhost" />
</bypasslist>
</defaultProxy>
and add the proxy.config into my app.config as a system.net configuration:
<system.net>
<defaultProxy configSource="proxy.config" />
</system.net>

App absolutely refuses to use proxy for localhost requests

I have Fiddler running on port 8888
Web.config:
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy bypassonlocal="False" proxyaddress="http://localhost:8888" usesystemdefault="False" autoDetect="False" />
</defaultProxy>
</system.net>
App code (specifies credentials for the API controller its talking to):
var wc = new WebClient();
wc.Proxy = new WebProxy(new Uri($"http://localhost:8888"), false);
wc.Credentials = new NetworkCredential("myuser", "mypass");
var response = wc.UploadString("http://localhost:11026/api/mycontroller/mymethod", "POST", request);
I cannot for the life of me get it to communicate via Fiddler so I can debug requests. Am I doing something wrong?
UPDATE
This information is supplied by Fiddler help but having used localhost.fiddler in both web.config and app code, still not being captured by Fiddler (and when Fiddler is closed it doesn't cause a connection failed error)
Solution 2: Use http://ipv4.fiddler
Use http://ipv4.fiddler to hit localhost on the IPv4 adapter. This
works especially well with the Visual Studio test webserver (codename:
Cassini) because the test server only listens on the IPv4 loopback
adapter. Use http://ipv6.fiddler to hit localhost on the IPv6 adapter,
or use http://localhost.fiddler to hit localhost using "localhost" in
the Host header. This last option should work best with IIS Express.
Rather than trying to send it via the proxy, send it via one of the fiddler loopbacks.
Such as http://fiddler.ipv4:11026 ... ...
Details are given here:
http://docs.telerik.com/fiddler/observe-traffic/troubleshooting/notraffictolocalhost
Shows how to set it up and capture traffic. It is the method I've used when I want to see traffic being passed between local web apis and my Mvc project

send message to azure service bus queue from web api

I am trying to get started with Azure Service Bus queues. following this article
https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues
the only difference is that I am trying to do this from within a web api.
The error I get is:
No connection could be made because the target machine actively refused it 40.84.xxx.xx:443
I'd appreciate any help or pointers!
Note: Console app works just fine following the above guide.
Updated 7/24, this is the code in my action method:
try
{
var connectionString =
"Endpoint=sb://xxxxx-test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=shared_access_key";
var queueName = "testqueue1";
var client =
QueueClient.CreateFromConnectionString(connectionString, queueName);
var message = new BrokeredMessage(eventMessage);
client.Send(message);
}
catch (Exception e)
{
//log exception
}
Update 7/25. I was able to make it work by setting defaultConfig entry as enabled in web.config:
<system.net>
<defaultProxy enabled="true"/>
</system.net>
No connection could be made because the target machine actively refused it 40.84.xxx.xx:443
Please check whether the outbound 443 port is blocked by your firewall.
Note: Console app works just fine following the above guide.
The default value of connectivity mode for Service Bus is AutoDetect. It will automatically selects between the Tcp and Http modes based on an auto-detection mechanism that probes whether either connectivity option is available for the current network environment. It maybe choose different modes for your Console App and Web API application. Try to set it to TCP explicitly in your Web API application before using the Service Bus Queue.
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Tcp;
I was able to make it work by setting defaultConfig entry as enabled in web.config:
<system.net>
<defaultProxy enabled="true"/>
</system.net>

A connection attempt failed because the connected party did not properly respond

I have a shared server on 1and1. In my MVC site, when I try to connect to another server outside I get this error:
An error occurred while sending the request. Unable to connect to the
remote server A connection attempt failed because the connected party
did not properly respond after a period of time, or established
connection failed because connected host has failed to respond
23.xxx.xxx.xxx:80
When I run it on my development machine locally it works fine, but when I upload it to server by FTP, it shows that error.
here is my code:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://OutsideServer.com", UriKind.Absolute);
var url = "GetData";
var stringContent = string.Format("\"id\":12");
StringContent content = new StringContent(stringContent);
var result = await client.PostAsync(url, content);
var jsondata = await result.Content.ReadAsStringAsync();
in another question I found this answer:
<configuration>
<system.net>
<defaultProxy>
<proxy
usesystemdefault = "false"
proxyaddress="http://proxyserver"
bypassonlocal="true"
/>
</defaultProxy>
</system.net>
</configuration>
But I don't know what proxy address should be.
I ran into the same issue after 5 years when trying to use it with asp.net core 3.1 mvc app. I used the following proxy setting as mentioned in their site https://www.ionos.co.uk/help/hosting/net/script-examples-for-establishing-external-http-connections-windows/
<proxy proxyaddress="http://winproxy.server.lan:3128"
bypassonlocal="true"
/>
The httpclient now looks like this and it works. Hope it might help someone.
services.AddHttpClient<MyNamedClient>()
.ConfigureHttpClient((provider, httpClient) =>
{
})
.ConfigurePrimaryHttpMessageHandler((handler) => new HttpClientHandler {
UseDefaultCredentials=true,
Proxy = new WebProxy("http://winproxy.server.lan:3128",true)
});
This is a 1&1 issue - they don't allow you to connect to servers outside their network :( had the same issue when calling a PayPal API. If you ring their support and explain they may take pity on you, but they didn't on me!
Update - found this from when I was digging around with Paypal last - this guy says you can create a proxy withing 1&1 - I haven't used this method myself: http://tofuculture.com/blog/post/Tips-Tricks-of-Using-11-Shared-Hosting-Environment.aspx

HTTP 407 proxy authentication error when calling a web service

I'm working on a .NET app that calls 3rd party web services over the internet. The services do not use SOAP, so we manually construct an XML request document, send it to the service via HTTP, and retrieve an XML response.
Our code is a Windows service that is run in the context of a normal Windows domain account, and sits behind a proxy server (Microsoft ISA Server) configured to require NTLM authentication. The account running our service has permission to access the internet through the proxy server.
The code looks like this:
// Create the request object.
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
// Configure for authenticating proxy server requiring Windows domain credentials.
request.Proxy = New WebProxy(proxyAddress) { UseDefaultCredentials = true };
// Set other required headers.
request.Accept = acceptableMimeType;
request.Headers.Add(HttpRequestHeader.AcceptCharset, acceptableCharset);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "none");
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-gb");
request.Headers.Add(HttpRequestHeader.CacheControl, "no-store");
request.Headers.Add(HttpRequestHeader.ContentEncoding, "none");
request.Headers.Add(HttpRequestHeader.ContentLanguage, "en-gb");
request.ContentType = requestMimeType;
request.ContentLength = requestBytes.Length;
// Make the method call.
using(Stream stream = request.GetRequestStream()) {
stream.Write(requestBytes, 0, requestBytes.Length);
}
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// Extract the data from the response without relying on the HTTP Content-Length header
// (we cannot trust all providers to set it correctly).
const int bufferSize = 1024 * 64;
List<byte> responseBytes = new List<byte>();
using(Stream stream = new BufferedStream(response.GetResponseStream(), bufferSize)) {
int value;
while((value = stream.ReadByte()) != -1) {
responseBytes.Add((byte) value);
}
}
This works fine if the proxy server is turned off, or the URL has been whitelisted as not requiring authentication, but as soon as authentication is active, it always fails with an HTTP 407 error.
I put the above code in a test harness, and tried every method I could think of for configuring the request.Proxy property, without success.
I then noticed that all the 3rd party web services that we have to call are HTTPS. When I tried accessing them as HTTP instead, the proxy authentication started working. Is there some extra hoop I have to jump through to get proxy authentication and HTTPS to play nicely?
PS: The same problems occur with the open source SmoothWall proxy server, so I can't just write it off as a bug in ISA Server.
PPS: I'm aware that you can configure proxy settings in app.config, but (a) doing it in code shouldn't make any difference, and (b) the application design requires that we read the proxy settings from a database at runtime.
Have you tried setting the proxy in the app.config ?
To disable the proxy, in the App.config file add the following configuration
<system.net>
<defaultProxy enabled="false" useDefaultCredentials="false">
<proxy/>
<bypasslist/>
<module/>
</defaultProxy>
</system.net>
To enable the proxy and to use the default proxy settings(specified in IE) add this configuration in your App.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy/>
<bypasslist/>
<module/>
</defaultProxy>
</system.net>
I did have a similar situation
Did you noticed it worked when you accessed the internet before you ran the code? and if you had not accessed the internet for ages (20mins for me) you got the error.
have you tried to set the proxy credentials directly?
//setup the proxy
request.Proxy = new WebProxy("proxyIp", 8080);
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
I hope this fixes your issue too
I think I will have to write off this question. My original posted code does appear to work sometimes. Our proxy server is extremely unreliable; one minute it will block an internet connection from any software, and the next it will allow it. The IT guys seem powerless to do anything about it, and we (everyone outside the IT department) have no authority to make changes to the network infrastructure.
If anyone has any ideas on how to "harden" my code to compensate for an unreliable proxy server, then I'd be interested to hear them. :-)
Is there something wrong with your proxy server's certificate? If your service can't establish HTTPS then it will throw an error.

Categories

Resources