gRPC - JsonTranscoding - IOException: Unable to read data from the transport connection - c#

I implemented JsonTranscoding
in my simple gRPC
application. I've a POST
api. When I test my POST
api using swagger, I could call it; but when I test it using Postman or
HttpClient (Acually calling api using code) I get two below exception:
IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.
and also:
SocketException: An established connection was aborted by the software in your host machine.
*** I have no firewall on my local machine.**

I figured out that my gRPC service does not support HTTP request and this makes problem. so I cofigured it to support HTTP1 and HTTP2. There is two ways to configure it:
Adding below code in Program.cs :
builder.WebHost.ConfigureKestrel((context, options) =>
{
options.ListenAnyIP(7013, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
listenOptions.UseHttps();
});
});
or in appsettings.json :
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1AndHttp2"
}
}

Related

"A connection attempt failed because the connected party did not properly respond after a period of time" using HTTPClient for calling 3rd party url

I am facing some issue when calling third party API in Azure environment.
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(tokenEndpoint, UriKind.Absolute))
{
Content = new FormUrlEncodedContent(payload)
};
using var responseMessages = await clienthttp.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false);
We are trying to access External 3rd party API url from AzureFunction in Azure Cloud.
Whenever we tried to do post request from Azure Function to 3rd party API, it gives the following error:
Error : “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.”
Its working fine in local system but gives error when deployed in Azure.
Also we have tried with Addition of SecurityProtocol TLS, Extend the API Request Time, HTTPClientFactory using POLLY, Enabled CORS Policy but none of them worked.
Is there any need of configuration between Azurefunction and 3rd party API in Azure.
Please check if the below steps help to fix the issue:
Try Whitelisting your IP Address in the Azure Function App > Networking > Access Restrictions
If you have integrated the Function App with Virtual Network, then check the NAT Gateway rules as well as whitelisting the static IP addresses on the Firewall side.

Xamarin forms and gRPC: The server returned an invalid or unrecognized response

I am trying to get a response from the gRPC service but I get the error that the server returned an invalid or unrecognized response when I make the call from a Xamarin application. However, if I use a WPF client, that use the same gRPC client library than the Xamarin application, it works as exepected, I get the response from the service.
The service code is this:
webBuilder.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Any, 5001, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
listenOptions.UseHttps("server.pfx", "1111");
});
});
webBuilder.UseStartup<Startup>();
Client library:
HttpClientHandler miHandler = new HttpClientHandler();
miHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
GrpcChannelOptions misOpciones = new GrpcChannelOptions() { HttpHandler = miHandler };
var miChannel = GrpcChannel.ForAddress("https://192.168.1.134:5001", misOpciones);
What I am doing wrong? At first I thought it was because from android I couldn't use http, that I need https, but now I am using https. It is true that I am ignoring any certificate from the server, could it be this the reason for that? But the error message it would be related with SSL or something like that, instead of telling that the response is not recognized.
Thanks.
EDIT: in the console aplication that hosts the service, I get this fail: HTTP/2 over TLS was not negotiated on an HTTP/2-only endpoint.
You could try to use Grpc.Core or gRPC-Web as it is mentioned in the documentation.
Calling gRPC over HTTP/2 with Grpc.Net.Client is currently not
supported on Xamarin. We are working to improve HTTP/2 support in a
future Xamarin release. Grpc.Core and gRPC-Web are viable alternatives
that work today.
And you may refer to https://stackoverflow.com/a/60362990/10768653.

C# HttpClient Multiple Get Requests at the same time giving System.Net.Sockets.SocketException (10060) Exception

As Suggested by #John Wu's Answer on Stackoverflow. I am using the following code to make concurrent HTTP Get Requests on the same host for sending SMS
public async Task SendBulk(List<string> recipentURLs)
{
using (var client = new HttpClient())
{
//Start requests for all of them
var requests = recipentURLs.Select(url => client.GetAsync(url)).ToList();
//Wait for all the requests to finish
await Task.WhenAll(requests);
}
}
Now I am having the exception saying
System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: Unable to read data from the transport connection: 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..
---> System.Net.Sockets.SocketException (10060): 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.
The API I am sending requests to doesn't require a response (as I am only using it to send sms).
I am using this in a backgroud job by using HangFire. So I am okay if it takes a long time.
What I am currently looking is an efficient way to send multiple HTTP Get Requests at the Same host.
How can I safely handle all these concurrent requests and retry if any of it fails?
Also I am currently researching that due HTTP Throttling I cannot use 2 connection to the same host?
Closed HttpClient instances leave sockets open in the TIME_WAIT state for a short period of time. If a code path that creates and disposes of HttpClient objects is frequently used, the app may exhaust available sockets. You should use HttpClientFactory to avoid that.
See the post Make HTTP requests using IHttpClientFactory in ASP.NET Core.

Connecting from HttpClient to API behind Azure FrontDoor using TLS 1.2

Azure Front Door is configured with minimum TLS 1.2.
The backend Azure App Service is also configured to use minimum TLS 1.2.
When running the .Net Framework 4.7.1 console app with the following code on Windows Server 2012 R2:
class Program
{
static async Task Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new HttpClient();
try
{
var OK = await client.GetAsync("https://foo-appservice.azurewebsites.net/"); // App service.
var NotOK = await client.GetAsync("https://foo.myfoo.io/"); // Front door.
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
}
I get the following exception on the second call.
An error occurred while sending the request.
The underlying connection was closed: An unexpected error occurred on a send.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Running this with curl from the same server works, however:
curl https://foo.myfoo.io/ -i --tlsv1.2 --tls-max 1.2
The same .net code runs fine from my other windows 10 laptop.
What can be the reason why the call fails on the windows server box?
Edit:
I think this has to do with custom domains, since performing a simple GET to the front door assigned domain works.
Turns out "someone" had disabled a lot of cipher suites on the Windows Server.
I used wireshark to look at the TLS handshake and noticed that the cipher suites listed at the Client Hello didn't match the servers.
So for anyone struggling with TLS errors, it can be worthwile to look at the TLS handshake in Wireshark!

Server frequently loses Azure SignalR connection

My ASP.NET Web API (target framework: .NET Framework 4.6.2) project frequently loses connection with Azure SignalR service (free tier). I have followed the example as shown in aspnet ‘chatroom’ example.
My client application is based on Angular JS. Messages are being send to the clients but after a few hours, the server connection with Azure SignalR service is lost and is not established again.
As far as I understand from the MS Azure SignalR Internals documentation:
If a server connection is disconnected for network issue,
the server connection starts reconnecting automatically.
The following error is returned back in response:
Azure SignalR Service is not connected yet, please try again later
However, this does not seem to be happening i.e. server connection with Azure SignalR service is not established again.
nuget packages:
Microsoft.AspNet.SignalR v2.4.0
Microsoft.AspNet.SignalR.Core v2.4.0
Microsoft.AspNet.SignalR.SystemWeb v2.4.0
Microsoft.Azure.SignalR.AspNet v1.0.0-preview1-10317
Microsoft.Azure.SignalR.Protocols v1.0.6
There is currently an issue with Microsoft.Azure.SignalR.AspNet v1.0.0-preview1-10317. The fix is planned to be released this week.
Have you added error handling code in your client like below-
// Define handlers for any errors
//
this.hubConnection.error((error: any) => {
// Push the error on our subject
//
this.hubConnection.start()
.done(() => {
this.startingSubject.next();
//Invoke connect method on Hub
// this.hubProxy.invoke("Connect", userId, usertype);
})
.fail((error: any) => {
this.startingSubject.error(error);
});
});
Also in case of closed connection code would be like
this.hubConnection.onclose(() => {
setTimeout(function(){
this.hubConnection.start()
.done(() => {
this.startingSubject.next();
//Invoke connect method on Hub
// this.hubProxy.invoke("Connect", userId, usertype);
})
.fail((error: any) => {
this.startingSubject.error(error);
});
},3000);
});
Hope it helps.
MV

Categories

Resources