HTTP Request Failing in Production - c#

My ASP.NET web app is interacting with an API and making calls to various endpoints.
When I hit the endpoints through Postman it's quick and successful. When I run the app locally it also works as expected. However, when I publish the app to Azure I'm having issues hitting the API and it's very inconsistent.
Sometimes it works and sometimes it doesn't. When it fails the call will hang up for a few seconds and then I get the following exception:
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
What I've come to notice through trial-and-error is that if I wait for around 10 seconds or so after each request it works. I tried using Thread.Sleep(10000) and Task.Delay(10000) to simulate me waiting the 10 seconds but those are causing issues (receiving the same connection attempt failed error).
using (HttpClient client = new HttpClient())
{
//Construct POST Request
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, Global.api + "/token");
req.Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
//Do POST Request
using (HttpResponseMessage response = await client.SendAsync(req, HttpCompletionOption.ResponseContentRead))
{
using (HttpContent content = response.Content)
{
//Store data retrieved from POST request
string strContent = await content.ReadAsStringAsync();
Token token = await content.ReadAsAsync<Token>();
}
}
}
Thread.Sleep(10000);

Related

C#: Http Get behavior varies in different LAN

I started an HTTP server in a local area network from C# as:
HttpListener listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
In another thread, it sends response as:
HttpListenerContext context = listener.GetContext();
context.Response.StatusCode = 200;
using (StreamWriter writer = new StreamWriter(context.Response.OutputStream)) {
writer.WriteLine(responseJson);
}
And in my client code, Http request is sent and processed as:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string result = await response.Content.ReadAsStringAsync();
This server-client application works well in one LAN. But after I copied the application to another machine in another LAN, the last line of client code (await response result) got error " The input was not in a correct format". I really have no idea what it is about. I visited the server url from web browser, the correct response could be retrieved. So this is more likely to be a client-side issue, I guess.
Any help is appreciate.

Long-waiting HttpClient aborted the connection in .NET Core 3.1

I have encountered a strange problem when using HttpClient,the code show below.
Environment: k8s
Internet: intranet
App: .NET Core 3.1
Code:
using (var httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(2, 0, 0);
using var httpContent = new StringContent(JsonConvert.SerializeObject(exportParameter), Encoding.UTF8, "application/json");
var httpResponseMessage = await httpClient.PostAsync($"{url}", httpContent);
}
This is a file export scene, if it's a small file export (the response is very fast, less than 5 minutes, most of this scene) -- never had any problems.
But when we perform a large file export(the response size is about 100MB and waiting time is more than one hour but less than two hours), the httpclient requester will prompt
The application aborted the connection
and the httpclient gets no response.
Does anyone know what is causing the problem?
Thanks

Timeout while making POST request with no authentication C#

I want to make a POST request to a rest service. There is no authentication, it has only two customized header. My code is below. I am getting the error :
An exception of type 'System.AggregateException' occurred in mscorlib.dll but was not handled in user code.
"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"
May you help ? What is wrong in the code ?
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("id", "8888");
client.DefaultRequestHeaders.Add("type", "CUSTOMER");
Uri uri = new Uri(requestUri);
var ob = new { id= "5", color= "pink" };
var transferJson = JsonConvert.SerializeObject(ob);
var content = new StringContent(transferJson, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = client.PostAsync(uri, content).Result;
Your code itself doesn't look faulty. The error message suggests that the request ran into a timout, which means that the HttpClient waits for a set period of time and terminates if the server doesn't respond. Have you tried pinging the server to make sure it's actually up and running?
It that's the case you could try to increase the timeout value of your HttpClient (see here https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=netframework-4.8).
Additionally you could try to send the request with another tool like Postman to see whether the issue lies within your code, your parameters (like timeout), or the server itself.

C# HttpClient Bad Request on second call

I've found with the below code that on any second httpclient request, I always get a 400 Bad Request.
I can confirm the API calls actually work and return a 200 - so if I flip them, the first call will return 200 second call, 400.
I can't figure out why this is the case.
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage blah = await client.GetAsync("api/subscriptions?account=eclipse&application=Sample");
HttpResponseMessage dfds = await client.GetAsync("api/subscriptions?account=eclipse");
...
}
It's hard to tell without seeing the controller function you're trying to call. What's probably happening is that the REST service is experiencing an exception on the server and is throwing back a 400.
What web server is the service using? Maybe it has some sort of simultaneous request blocking. You could try not using async.
What I would do is open up Fiddler (http://www.telerik.com/fiddler) and look at the network traffic. Look at the response from the web server and see if there is any exception data there.

Need to call method as soon as server starts responding to my HttpWebRequest

I need to call a method in new thread for ex: mymethod() as soon as server starts responding to my HttpWebRequest.
I am using below to send http requst and getting response.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MyUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Now what i need is for my request when server starts responding as soon as i need to call a method mymethod() in new thread. But problem is I don't know how to detect that server has started responding (started responsestream ) to my request.
What is the way that tell me that server started responding and I can call my method.
Target framework: is .net framework 4.5 and my project is Windows Form application.
The closest I can think of is using HttpClient and passing a HttpCompletionOption.ResponseHeadersRead, so you can start receiving the request once the headers are sent and later start processing the rest of the response:
public async Task ProcessRequestAsync()
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(
url,
HttpCompletionOption.ResponseHeadersRead);
// When we reach this, only the headers have been read.
// Now, you can run your method
FooMethod();
// Continue reading the response. Change this to whichever
// output type you need (string, stream, etc..)
var content = response.Content.ReadAsStringAsync();
}

Categories