I have been looking at this for a long time, looking through all the different posts on the internet to see if I could find someone with the same issue but somehow I seem to be the only have having this issue.
I have an ASP.net Core server running the basic greeter service of Grpc.
Calling this server using the program "BloomRPG" work great, and has excellent response times.
However when I try to do the same from my own written (very basic) client I get the following errors:
On the Client:
dbug: Grpc.Net.Client.Internal.GrpcCall[1]
Starting gRPC call. Method type: 'Unary', URI: 'https://www.MYSERVER.com:50005/greet.Greeter/SayHello'.
dbug: Grpc.Net.Client.Internal.GrpcCall[18]
Sending message.
trce: Grpc.Net.Client.Internal.GrpcCall[21]
Serialized 'TestService1.HelloRequest' to 15 byte message.
trce: Grpc.Net.Client.Internal.GrpcCall[19]
Message sent.
fail: Grpc.Net.Client.Internal.GrpcCall[6]
Error starting gRPC call.
System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: The response ended prematurely.
at System.Net.Http.HttpConnection.FillAsync()
at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Grpc.Net.Client.Internal.GrpcCall2.RunCall(HttpRequestMessage request, Nullable1 timeout) info: Grpc.Net.Client.Internal.GrpcCall[3] Call failed with gRPC error status. Status code: 'Internal', Message: 'Error starting gRPC call. HttpRequestException: An error occurred while sending the request. IOException: The response ended prematurely.'. dbug: Grpc.Net.Client.Internal.GrpcCall[4] Finished gRPC call. dbug: Grpc.Net.Client.Internal.GrpcCall[8] gRPC call canceled. Unhandled exception. Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: An error occurred while sending the request. IOException: The response ended prematurely.", DebugException="System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The response ended prematurely. at System.Net.Http.HttpConnection.FillAsync() at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Grpc.Net.Client.Internal.GrpcCall2.RunCall(HttpRequestMessage request, Nullable1 timeout)")
at GrpcGreeterClient.Program.Main(String[] args) in C:\Users\MYUSERNAME\source\repos\grpc\TestgrpcClient\TestgrpcClient\Program.cs:line 64
at GrpcGreeterClient.Program.(String[] args)
s
on the server:
fail: Microsoft.AspNetCore.Server.Kestrel[0]
HTTP/2 over TLS was not negotiated on an HTTP/2-only endpoint.
Since I am succesfully calling the service with BloomRPC I suppose the issue is with my client:
Client code:
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var loggerFactory = LoggerFactory.Create(logging =>
{
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Trace);
});
var httpclient = new HttpClient();
httpclient.DefaultRequestVersion = new Version(2, 0);
using var channel = GrpcChannel.ForAddress("https://www.MYSERVER.com:50005",
new GrpcChannelOptions { LoggerFactory = loggerFactory, HttpClient = httpclient});
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + reply.Message);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
anyone have any idea what I could try next?
I feel like I have exhausted all my options :(
Thanks to #jdweng I figured out what was causing the issue.
a mandatory company proxy server was interfering, setting the UseProxy = false in the httpclienthandler fixed the issue for me and I am now able to call my gRPC server without problems!
Related
I have a WCF service and I created its client using "Add WCF Service Reference" it has a custom SSL client certificate and I added it to client. It works on my own computer but when I move it to my server it doesn't work.
The code is a very simple function call like this:
using ConsoleAppFramework.MyServiceReference;
using System;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Security;
using System.Threading.Tasks;
namespace ConsoleAppFramework
{
internal class Program
{
static async Task Main(string[] args)
{
SoapServicesClient client = new SoapServicesClient();
client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(#"C:\My-Client-Cert.p12", "pass");
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
{
CertificateValidationMode = X509CertificateValidationMode.None,
RevocationMode = X509RevocationMode.NoCheck
};
client.Open();
var res = await client.loginStaticAsync(Array.Empty<contextEntry>(), new userInfoRequestBean()
{
username = "user",
password = "pass"
});
client.Close();
Console.WriteLine(res.#return.sessionId);
}
}
}
When I use .NET Framework 4.7.2 it work perfectly and I get the result but with .NET 6 I get this error:
Unhandled exception. System.ServiceModel.CommunicationException: An error occurred while sending the request.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine..
---> System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine.
--- End of inner exception stack trace ---
at System.Net.Security.SslStream.<FillBufferAsync>g__InternalFillBufferAsync|215_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)
at System.Net.Security.SslStream.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)
at System.Net.Http.HttpConnection.FillAsync()
at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
--- End of inner exception stack trace ---
at ConsoleAppCore3_1.Program.Main(String[] args) in C:\Users\......\Program.cs:line 45
at ConsoleAppCore3_1.Program.<Main>(String[] args)
Is there anything changed between WCF client service on .NET Framework 4.7.2 and .NET 6?
What I tried
I try this with .NET Core 3.1 and I get the same error, only with .NET Framework I can get it to work.
The server is a Windows Server 2019, the code works on my computer with .NET 6 and .NET Core 3.1 but on my server these two versions throw the same error.
It has to do something that is closing your active http connection.
try this :
_client.DefaultRequestHeaders.ConnectionClose = true;
or you can use fiddler to further investigate what is happening.
After moving from the.NET Framework to the.NET Core, not all features are available. You can try using CoreWCF instead of the original functionality, see this article for more information.
I have a Blazor app and Just I want to know how we can check if the server is running or stopped to do better error handling
I'm using HttpClient PostAsJsonAsync for example for authnthication in Login and when the server is stopped I get an error
"Failed to load resource: net::ERR_CONNECTION_REFUSED"
and
"crit:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: TypeError: Failed to fetch System.Net.Http.HttpRequestException: TypeError: Failed to fetch
---> System.Runtime.InteropServices.JavaScript.JSException: TypeError: Failed to fetch at
System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken) --- End of inner
exception stack trace --- at
System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken) at
Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken) at
Toolbelt.Blazor.HttpClientInterceptorHandler.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken) at
Toolbelt.Blazor.HttpClientInterceptorHandler.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken) at
System.Net.Http.HttpClient.g__Core|83_0(HttpRequestMessage
request, HttpCompletionOption completionOption,
CancellationTokenSource cts, Boolean disposeCts,
CancellationTokenSource pendingRequestsCts, CancellationToken
originalCancellationToken)"
I have an Http Interceptor Service in my Blazor app and I want to check the connection before any action
I use HttpClient to get the content of the pages on the internet and was faced with weird behavior.
Some sites load perfectly, but some requests fail by timeout. The thing is that the links work perfectly in the browser.
E.g. I have the following link: https://www.luisaviaroma.com/en-gb/shop/women/shoes?lvrid=_gw_i4. I can open it in the browser, but my code doesn't work:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://www.luisaviaroma.com/en-us/sw/women?lvrid=_gw");
What can be the cause of it?
Probably the issue is with the _ symbol? How should I fix it then?
I also tried to use 3rd party libraries like RestSharp but got the same result.
The exception is:
System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.
---> System.TimeoutException: The operation was canceled.
---> System.Threading.Tasks.TaskCanceledException: The operation was canceled.
---> System.IO.IOException: Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request..
---> System.Net.Sockets.SocketException (995): The I/O operation has been aborted because of either a thread exit or an application request.
--- End of inner exception stack trace ---
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Int32>.GetResult(Int16 token)
at System.Net.Security.SslStream.EnsureFullTlsFrameAsync[TIOAdapter](TIOAdapter adapter)
at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter adapter, Memory`1 buffer)
at System.Net.Http.HttpConnection.InitialFillAsync(Boolean async)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at System.Net.Http.HttpClient.HandleFailure(Exception e, Boolean telemetryStarted, HttpResponseMessage response, CancellationTokenSource cts, CancellationToken cancellationToken, CancellationTokenSource pendingRequestsCts)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Suits.Scheduler.SchedulerHostedService.UpdateClothesLinksAsync(SuitsDbContext dbContext) in C:\Repo\server\src\Suits.Scheduler\SchedulerHostedService.cs:line 98
I got a 403 Error, when not setting appropriate values for the Header-Accept field.
The result is a text/html, so you need to add the appropriate Header:
HttpRequestMessage msg = new HttpRequestMessage(
HttpMethod.Get,
"https://www.luisaviaroma.com/en-gb/shop/women/shoes?lvrid=_gw_i4"
);
msg.Headers.Add("Accept", "text/html");
HttpClient client = new HttpClient();
var response = client.SendAsync(msg).Result;
EDIT:
In the given case, OP needs to add the Accept-Encoding header two. The answer of D A pointed this out. Code to add the field:
msg.Headers.Add("Accept-Encoding", "br");
This is the proper request that will return a 200 OK code:
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get,"https://www.luisaviaroma.com/en-us/sw/women?lvrid=_gw");
msg.Headers.Add("Accept", "text/html");
msg.Headers.Add("accept-encoding", "gzip, deflate, br");
HttpClient client = new HttpClient();
var response1 = client.SendAsync(msg).Result;
The response is send compressed and that is why you have issues with it.
I want to retrieve the content of a page with httpclient. I did a simple method, which works well on visual studio.
private async Task<string> Connection(string Url)
{
using HttpClient client = new();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 OPR/77.0.4054.277");
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store, must-revalidate");
client.DefaultRequestHeaders.Add("Accept-Language", "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7");
client.DefaultRequestHeaders.Add("Pragma", "no-cache");
double timestamp = GlobalMethod.Timestamp();
string json = await client.GetStringAsync(Url);
return json;
}
But when I run my application on a linux VPS (Ubuntu, host OVH, .NET 5), Httpclient returns an error timeout.
On my VPS, the ping to the url I want to retrieve, and CURL function, works fine. But not the Httpclient.
Same settings of my Postman request, and no problem with it.
Do you have an idea of the problem ?
It looks a lot like this topic, without me understanding how to solve it: httpClient call in C# goes to timeout, while cUrl is working
API link : https://api.store.nvidia.com/partner/v1/feinventory?skus=FR~NVGFT070~NVGFT080~NVGFT090~NVLKR30S~NSHRMT01~NVGFT060T~187&locale=FR
Thanks !
Error with timeout:
System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.
---> System.TimeoutException: The operation was canceled.
---> System.Threading.Tasks.TaskCanceledException: The operation was canceled.
---> System.IO.IOException: Unable to read data from the transport connection: Operation canceled.
---> System.Net.Sockets.SocketException (125): Operation canceled
--- End of inner exception stack trace ---
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)
at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter adapter, Memory`1 buffer)
at System.Net.Http.HttpConnection.FillAsync(Boolean async)
at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean async, Boolean foldedHeadersAllowed)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.GetStringAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at Castiel_Bot_Discord.Modules.NvidiaCommand.Connection(String Url) in C:\Users\gaeta\source\repos\Castiel_Bot_Discord\Castiel_Bot_Discord\Modules\NvidiaCommand.cs:line 114
at Castiel_Bot_Discord.Modules.NvidiaCommand.SearchGpu(String args) in C:\Users\gaeta\source\repos\Castiel_Bot_Discord\Castiel_Bot_Discord\Modules\NvidiaCommand.cs:line 42
Same issue on my Debian machine. Suddenly timeout exception occured for https requests, but I did not performed any configuration steps before at all. The app just stopped to work!
What I've found out to solve:
https://github.com/dotnet/runtime/issues/47267
According to that you need to disable ipv6. For my host I've changed sysctl.conf as described here: https://wiki.it-kb.ru/unix-linux/debian/how-to-turn-off-ipv6-in-debian-linux
Now the timeout issue solved for me.
At port "81", i have automation anywhere control room and want to make a api call to get authentication token.I tried below code locally its working fine but when i deploy in azure app service getting error
using (HttpClient httpClient = new HttpClient())
{
var authenticateClient = new RestClient("ipaddress:81/v1/authentication");
var authenticateRequest = new RestRequest(Method.POST);
authenticateRequest.AddHeader("Content-Type", AAConstant.fileFormat);
authenticateRequest.Parameters.Clear();
authenticateRequest.AddJsonBody(new
{
username = "******",
password = "*******"
});
IRestResponse authenticateResponse = authenticateClient.Execute(authenticateRequest);
StackTrace :
System.Net.WebException: An attempt was made to access a socket in a way forbidden by its access permissions An attempt was made to access a socket in a way forbidden by its access permissions ---> System.Net.Http.HttpRequestException: An attempt was made to access a socket in a way forbidden by its access permissions ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at System.Net.HttpWebRequest.SendRequest()
at System.Net.HttpWebRequest.GetResponse()
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at RestSharp.Http.GetRawResponse(HttpWebRequest request)
at RestSharp.Http.GetResponse(HttpWebRequest request)
Changed azure app service plan and also disabled antivirus,firewall but did not work .
Any help !!