Request timed out while using Post method HttClient in C# - dotnet-httpclient

In my application, I am using a code piece to send a content to a web proxy with a URL with an interval of 2 seconds between each post. The message to post in the below code is given as static string, but will be dynamic in the original application code.
for (ic = 0; ic < 30; ic++)
{
using(HttpClient httpClient = new HttpClient())
{
Encoder encoder = new Encoder(); //This is a class which we created
AuthorizationHeaders authorizationHeaders = encoder.getAuthorization(PARTNER_ID, PARTNER_KEY, URL, "POST", "application/xml");
httpClient.DefaultHeaders.Add("Accept", "*/*");
httpClient.DefaultHeaders.Add("Authorization", authorizationHeaders.getAuthorizationHeader());
httpClient.DefaultHeaders.Add("Expires", authorizationHeaders.getExpiresHeader());
httpClient.DefaultHeaders.Add("origPartnerId", "MyWebSite");
httpClient.DefaultHeaders.Add("appId", "440");
httpClient.DefaultHeaders.Add("Content-Type", "application/xml");
string inputUrl = ConfigurationManager.AppSettings["url"];
String detailRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Message><Details><Name>Bob</Name><Age>45</Age></Details></Message>";
var content = HttpContent.Create(detailRequest, Encoding.UTF8, "application/xml");
response = httpClient.Post(inputUrl, content).EnsureStatusIsSuccessful();
Thread.Sleep(2000);
}
}
But I am getting the below exception when contacting the proxy. I am not getting it all the time, the message does go through some time, but eventually, this exception comes.
GetResponse timed out ---> System.TimeoutException: GetResponse timed out ---> System.Net.WebException ---> System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.Http.HttpWebRequestTransportStage.HttpTransportAsyncResult.PopulateWebResponseSync(WebRequest request, IAsyncResult result)
at Microsoft.Http.HttpWebRequestTransportStage.HttpTransportAsyncResult.PopulateWebResponse(HttpTransportAsyncResult self, IAsyncResult result, Func`3 getResponse)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at Microsoft.Http.AsyncResult.End[TAsyncResult](IAsyncResult result, Boolean throwException)
at Microsoft.Http.HttpWebRequestTransportStage.EndProcessRequestAndTryGetResponse(IAsyncResult result, HttpResponseMessage& response, Object& state)
at Microsoft.Http.HttpWebRequestTransportStage.ProcessRequestAndTryGetResponse(HttpRequestMessage request, HttpResponseMessage& response, Object& state)
at Microsoft.Http.HttpStageProcessingAsyncResult.NextRequest(HttpStageProcessingAsyncResult self)
--- End of inner exception stack trace ---
at Microsoft.Http.HttpStageProcessingAsyncResult.Complete(HttpStage stage, Exception e)
at Microsoft.Http.HttpStageProcessingAsyncResult.NextRequest(HttpStageProcessingAsyncResult self)
at Microsoft.Http.HttpClient.Send(HttpRequestMessage request)
at Microsoft.Http.HttpClient.Send(HttpMethod method, Uri uri, RequestHeaders headers, HttpContent content)
at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, Uri uri, HttpContent body)
at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, String uri, HttpContent body)
But this proxy is just a redirection to another one. So I tried directly to that one also. There, I was able to do this 2 or 3 times successfully but it generated another exception after that. I tried again, but this time, the exception came for the first try itself. I waited for some time and then tried again, and surprisingly, it did go through 2 or 3 times and then again the exception came. The exception that I am getting this time is different and it is this...
Microsoft.Http.HttpStageProcessingException ---> System.Net.WebException ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly. at System.Net.HttpWebRequest.GetResponse() at Microsoft.Http.HttpWebRequestTransportStage.HttpTransportAsyncResult.PopulateWebResponseSync(WebRequest request, IAsyncResult result) at Microsoft.Http.HttpWebRequestTransportStage.HttpTransportAsyncResult.PopulateWebResponse(HttpTransportAsyncResult self, IAsyncResult result, Func3 getResponse) --- End of inner exception stack trace --- at Microsoft.Http.AsyncResult.End[TAsyncResult](IAsyncResult result, Boolean throwException) at Microsoft.Http.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.Http.AsyncResult1.End(IAsyncResult result) at Microsoft.Http.HttpWebRequestTransportStage.EndProcessRequestAndTryGetResponse(IAsyncResult result, HttpResponseMessage& response, Object& state) at Microsoft.Http.HttpWebRequestTransportStage.ProcessRequestAndTryGetResponse(HttpRequestMessage request, HttpResponseMessage& response, Object& state) at Microsoft.Http.HttpStageProcessingAsyncResult.NextRequest(HttpStageProcessingAsyncResult self) --- End of inner exception stack trace --- at Microsoft.Http.HttpStageProcessingAsyncResult.Complete(HttpStage stage, Exception e) at Microsoft.Http.HttpStageProcessingAsyncResult.NextRequest(HttpStageProcessingAsyncResult self) at Microsoft.Http.HttpStageProcessingAsyncResult..ctor(HttpStageProcessingAsyncState state, AsyncCallback callback, Object user) at Microsoft.Http.HttpClient.Send(HttpRequestMessage request) at Microsoft.Http.HttpClient.Send(HttpMethod method, Uri uri, RequestHeaders headers, HttpContent content) at Microsoft.Http.HttpClient.Send(HttpMethod method, Uri uri, HttpContent content) at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, Uri uri, HttpContent body) at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, String uri, HttpContent body) at Microsoft.Http.HttpMethodExtensions.Post(HttpClient client, String uri, HttpContent body)
Any help in this regard would be greatly appreciated because I am after this for the past few days and I have read some articles and even questions in stackoverflow also, but nothing helped me. Thanks in advance...

The proxy rules of some companies will cause problems with POST requests.
GET requests work fine. Check that your OS proxy setting is disabled.
Windows 7: Control Panel > Internet Options > Connections (Tab).
Then click on the "LAN settings" button and then uncheck "Use a proxy server for your LAN".
Alternatively, try and get your Network Admins to add the connection that you are using to the exclusion list.

Related

openshift - container ssl request error - HttpClient XML

I try to send data to soap api .
In My development computer , there is no problem . I can take the response (before docker build).
Again in My computer , there is no problem in with docker run command. I can take the response.
But when I pull the run this container in openshift server , I can not take the response.
The error message is :
"The SSL connection could not be established, see inner exception.
---##--- System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer.\n --->
System.Net.Sockets.SocketException (104): Connection reset by peer\n
--- End of inner exception stack trace ---\n at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError
error, CancellationToken cancellationToken)\n at
System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16
token)\n at
System.Net.Security.SslStream.g__InternalFillHandshakeBufferAsync|182_0[TIOAdapter](TIOAdapter
adap, ValueTask`1 task, Int32 minSize)\n at
System.Net.Security.SslStream.ReceiveBlobAsync[TIOAdapter](TIOAdapter
adapter)\n at
System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter
adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean
isApm)\n at
System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean
async, Stream stream, SslClientAuthenticationOptions sslOptions,
CancellationToken cancellationToken)"
My code :
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback =
(sender,cert, chain, sslPolicyErrors) => { return true; };
HttpClient client = new HttpClient(clientHandler);
var stringContent = new StringContent(postData, encoding, "application/xml");
var response = await client.PostAsync(_Host,stringContent);

What are the urls required to unblock through firewall in corporate network for accessing for Google Translate API (Advanced Version)?

What are the urls required to unblock through firewall in corporate network for accessing for Google Translate API (Advanced Version)?
Right now unblocked are:
*.googleapis.com and accounts.google.com
But still I get below error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Grpc.Core.RpcException: Status(StatusCode="Unavailable", Detail="failed to connect to all addresses", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {​​​​​​​​"created":"#1612337108.132000000","description":"Failed to pick subchannel","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\ext\filters\client_channel\client_channel.cc","file_line":4090,"referenced_errors":[{​​​​​​​​"created":"#1612337108.132000000","description":"failed to connect to all addresses","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\ext\filters\client_channel\lb_policy\pick_first\pick_first.cc","file_line":394,"grpc_status":14}​​​​​​​​]}​​​​​​​​") at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Grpc.Core.Internal.AsyncCall2.UnaryCall(TRequest msg) at Grpc.Core.DefaultCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method2 method, String host, CallOptions options, TRequest request) at Grpc.Core.Interceptors.InterceptingCallInvoker.b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext2 ctx) at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext2 context, BlockingUnaryCallContinuation2 continuation) at Grpc.Core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method2 method, String host, CallOptions options, TRequest request) at Google.Cloud.Translate.V3.TranslationService.TranslationServiceClient.TranslateText(TranslateTextRequest request, CallOptions options) at Google.Api.Gax.Grpc.ApiCall.GrpcCallAdapter2.CallSync(TRequest request, CallSettings callSettings) at Google.Api.Gax.Grpc.ApiCallRetryExtensions.<>c__DisplayClass1_02.b__0(TRequest request, CallSettings callSettings) at ABG.Foundation.LanguageTranslator.GoogleTranslator.TranslateData(String sourceLanguage, String targetLanguage, List1 content) in D:\a\1\s\src\Foundation\LanguageTranslator\code\GoogleTranslator\GoogleTranslator.cs:line 106 at ABG.Foundation.LanguageTranslator.GoogleTranslator.TranslateData(List1 items, String sourceLanguage, String targetLanguage) in ...
NOTE: Same code and setup works fine outside the corporate network.

Getting Error while running Integration Test for Web API core with swagger

I am getting below errors while executing my integration test for one of method to post the data in the dynamics crm. This is the first time i am writing integration test where my project is web api using to swagger and some of the azure resources like key vault, active directory.
While executing the Get call it seems to run fine all the steps are performed and getting results as well. But for Post call i can see the call is successful and database is inserted record for the latest call but while returning execustion point back to my integration test from my PostAsync method it fails in between.
Below is the error:
Message:
System.IO.IOException : The request was aborted or the pipeline has finished
Stack Trace:
ResponseStream.CheckNotComplete()
ResponseStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
ErrorHandller.InvokeAsync(HttpContext context)
AuthenticationMiddleware.Invoke(HttpContext context)
StaticFileMiddleware.Invoke(HttpContext context)
SwaggerUIMiddleware.Invoke(HttpContext httpContext)
SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
CorrelationIdMiddleware.Invoke(HttpContext context, ICorrelationContextFactory correlationContextFactory)
<<SendAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
ClientHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
GeoIntegrationTest.Test_AddState() line 72
--- End of stack trace from previous location where exception was thrown ---
and the code is as below
public async Task Test_AddState()
{
try
{
var data = new StateRequestModel
{
StateCode = "AL",
Name ="Alabama",
}
};
ByteArrayContent byteContent = BuildRequestObject(data);
var response = await httpClient.PostAsync("api/Geo/AddState", byteContent);
var result = response?.Content.ReadAsStringAsync().Result;
var addStateReposne = (ResponseModel<List<string>>) JsonConvert.DeserializeObject(result);
Assert.NotNull(result);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
catch (Exception ex)
{
throw;
}
}
Please help me to fix this issue and advice me if i can improve the code quality.
So, I got it resolved myself only. The problem was with the Timeout due to some long running process which was running more than default timeout of the HttpClient object.
client.Timeout = System.TimeSpan.FromMinutes(5);
Thanks everyone!!!

MVC Can't Access WCF Data Services

I've added a WCF Data Service (v5.6) called test.svc to the root of my MVC app but I can't seem to get my routing figured out so that I can access it. Below are the results I get back in the browser when I go to http:/test.svc along with my route code and test.svc file.
route table entry (first route rule I add):
routes.IgnoreRoute("{resource}.svc/{*pathInfo}");
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class test : DataService<MyEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
config.UseVerboseErrors = true;
}
Error shown in browser:
The server encountered an error processing the request. The exception
message is 'Expression of type
'System.Data.Entity.Core.Objects.ObjectContext' cannot be used for
return type 'System.Data.Objects.ObjectContext''. See server logs for
more details. The exception stack trace is:
at System.Linq.Expressions.Expression.ValidateLambdaArgs(Type
delegateType, Expression& body, ReadOnlyCollection1 parameters) at
System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body,
String name, Boolean tailCall, IEnumerable1 parameters) at
System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body,
Boolean tailCall, IEnumerable1 parameters) at
System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body,
ParameterExpression[] parameters) at
System.Data.Services.Providers.DbContextHelper.CreateDbContextAccessor(Type
type) at
System.Data.Services.Providers.DbContextHelper.GetDbContextAccessor(Type
type) at
System.Data.Services.Providers.DbContextHelper.IsDbContextType(Type
type) at
System.Data.Services.DataService1.CreateMetadataAndQueryProviders(IDataServiceMetadataProvider&
metadataProviderInstance, IDataServiceQueryProvider&
queryProviderInstance, Object& dataSourceInstance, Boolean&
isInternallyCreatedProvider) at
System.Data.Services.DataService1.CreateProvider() at
System.Data.Services.DataService1.EnsureProviderAndConfigForRequest()
at System.Data.Services.DataService1.HandleRequest() at
System.Data.Services.DataService1.ProcessRequestForMessage(Stream
messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] ,
Object[] ) at
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
instance, Object[] inputs, Object[]& outputs) at
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&
rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
isOperationContextSet)
Looks like WCF DS and EF 6 are incompatible and there's no timeframe for when, or if, they might fix things.
http://social.msdn.microsoft.com/Forums/en-US/4aa92957-22de-4445-aecd-2871982afe28/eta-on-entity-framework-version-6-provider?prof=required

Uploading xml with Monotouch fails on the device

I am trying to send an XML via web client on Monotouch. Although everything is working on the iOS simulator I get an exception when the app is running on the device. Here is the code.
try
{
Byte[] sendData = System.Text.Encoding.UTF8.GetBytes(someXML) ;
WebClient client = new WebClient();
Byte[] forResp;
client.Headers.Add("Content-Type","text/xml");
bresp = wc.UploadData(URL, sendData);
string resp = System.Text.Encoding.ASCII.GetString(forResp);
XmlDocument xresp = new XmlDocument();
xresp.LoadXml(resp);
return xresp;
}
catch
{
// error
}
I tried the WebClient because I had the same issue with the HttpWebRequest.
Exception:
The request timed out
System.Net.WebException: The request timed out
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00065] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:830
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:836
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:1433
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:866
at System.Net.WebClient.UploadDataCore (System.Uri address, System.String method, System.Byte[] data, System.Object userToken) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:462
at System.Net.WebClient.UploadData (System.Uri address, System.String method, System.Byte[] data) [0x00035] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:441
The stacktrace tells us that the timeout occurs when WebClient tries to get a response from the server (and not when uploading the data to the server). That means access to the server is not the issue (and why stacktraces are very useful ;-)
The next steps depends if you have control, or not, of the server. If you control the server then check it's logs to find the request and see how it was handled. If possible also ensure you received/decoded the data identically between the simulator and device.
If you do not control the server then it's harder to know what's going on inside it. E.g. maybe it did not like the request (i.e. the server code can decide not to answer based on any condition, including the user-agent).
In such case using a tool, like wireshark, is often your best bet. Compare the session from the iOS simulator and from the device.
Is the request identical ? e.g. the data you uploaded could be different due to something else;
Is the server answering for the device ? with the same status code ? in the same time frame ?
If everything is identical then you might have found a bug. Please report it (along with the above informations and files) to http://bugzilla.xamarin.com
Otherwise you should have more precise clues to debug the issue and/or update the question to be more specific :-)

Resources