I'm trying to do an httpclient postasync and it works when I run it locally but not after I publish it.
public async Task<OrderRecord> GetOrderRecord(CheckOutRecord checkOutRecord)
{
OrderRecord orderRecord = new OrderRecord();
using (var client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.Timeout = TimeSpan.FromMilliseconds(100000);
HttpResponseMessage response = await client.PostAsJsonAsync("http://somewhere.com/Test/TestCheckout/", checkOutRecord);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
orderRecord = JsonConvert.DeserializeObject<OrderRecord>(result);
}
else
{
logger.Info(response.RequestMessage);
}
}
catch(HttpRequestException ex)
{
logger.Error(ex);
logger.Error("GetORderRecord failed. CheckOutRecord: " + checkOutRecord);
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
return orderRecord;
}
Here is the error message:
System.Net.Http.HttpRequestException: An error occurred while sending the request. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: 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 "server ip address"
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at MotorcraftCheckoutService.WebApplication.Controllers.OrderController.d__8.MoveNext()
Any idea's? If I run it locally and point it to the remote location it works. If I run it and point it to my machine it works. Does not work after I publish to the webserver.
Related
I’m trying to send a stream from client to server from a dotnet client to another dotnet server through sending an invocation to a method on server hub as follows:
// Method on Server Hub which should read the stream
public async Task UploadChannelReader(ChannelReader<string> stream, CancellationToken cancellationToken)
{
while (await stream.WaitToReadAsync(cancellationToken))
{
var item = await stream.ReadAsync(cancellationToken);
Console.WriteLine(item);
}
}
My implementation on dotnet client is as shown below:
// My method on dotnet client which used to invoke method on server
public async Task SendChannelStream(CounterInput counter, CancellationToken cancellationToken)
{
if (_hubConnection.State == HubConnectionState.Disconnected)
{
await _hubConnection.StartAsync();
}
var channel = Channel.CreateBounded<string>(10);
await _hubConnection.SendAsync(ServerChatEvents.UploadChannelReader, channel.Reader, cancellationToken);
await WriteToChannel(channel.Writer, counter, cancellationToken);
}
private async Task WriteToChannel(ChannelWriter<string> writer, CounterInput counter, CancellationToken cancellationToken)
{
Exception writeException = null;
try
{
await writer.WriteAsync("This is the first item sent from client to server", cancellationToken);
await writer.WriteAsync("This is the second item sent from client to server which can be received immidiately", cancellationToken);
await Task.Delay(counter.Delay, cancellationToken);
await writer.WriteAsync("This is the third item sent from client to server after a delay", cancellationToken);
await writer.WriteAsync("After this item we complete the writer and so the reader should mark completed!", cancellationToken);
}
catch (System.Exception ex)
{
writeException = ex;
Console.WriteLine(ex.Message);
}
finally
{
writer.Complete(writeException);
}
}
Where _hubConnection is a HubConnection to the Server hub.
The code does not work and I am not sure even if it cancelled in dotnet client or dotnet hub server.
But after removing the cancellationToken from the server hub method signature it works.
I think this is the correct behaviour since the cancellation from client is equal to not sending stream anymore which catch by server code automatically due to async nature of channel reader/writer or IAsyncEnumerable. But from a debugging point of view, it is really hard to find it out for me (...it has taken one full day!).
My questions are:
Why in the case of using the cancellation token in hub method signature, it doesn't work? (seems it cancels just right after calling the method)
Where does the cancellation take place? In dotnet client or in hub?
I am working on an API but I get this error whenever I try to connect to it:
Request starting HTTP/1.1 GET https://localhost:5061/api/machine
info: System.Net.Http.HttpClient.IdentityModel.AspNetCore.OAuth2Introspection.BackChannelHttpClientName.LogicalHandler[100]
Start processing HTTP request GET https://localhost:5001/.well-known/openid-configuration
info: System.Net.Http.HttpClient.IdentityModel.AspNetCore.OAuth2Introspection.BackChannelHttpClientName.ClientHandler[100]
Sending HTTP request GET https://localhost:5001/.well-known/openid-configuration
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Error parsing discovery document from https://localhost:5001: Error connecting to https://localhost:5001/.well-known/openid-configuration. The SSL connection could not be established, see inner exception..
at IdentityModel.AspNetCore.OAuth2Introspection.PostConfigureOAuth2IntrospectionOptions.GetIntrospectionEndpointFromDiscoveryDocument(OAuth2IntrospectionOptions options)
at IdentityModel.AspNetCore.OAuth2Introspection.PostConfigureOAuth2IntrospectionOptions.InitializeIntrospectionClient(OAuth2IntrospectionOptions options)
at IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler.LoadClaimsForToken(String token)
at IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 145.1044ms 500 text/plain
I am using IdentityModel.AspNetCore.OAuth2Introspection but there is no option there to configure a Backchannel HTTP Handler like the ones in JwtBearer.
I want to bypass certificate validation in OAuth2Introspection in development, something like the code below:
.AddOAuth2Introspection("introspection", options =>
{
// SOME INTROSPECTION CODES
options.BackchannelHttpHandler = new SocketsHttpHandler
{
SslOptions = new SslClientAuthenticationOptions
{
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}
};
// MORE INTROSPECTION CODES
});
resolved it by using ConfigurePrimaryHttpMessageHandler extension method
services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName)
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new SocketsHttpHandler
{
SslOptions = new SslClientAuthenticationOptions
{
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}
};
});
I have .NET Core 1.1 API and i am handling the error in startup.cs as below. I am using Serilog
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime, IRequestContext requestContext)
{
loggerFactory.AddSerilog();
// Ensure any buffered events are sent at shutdown
appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);
var logger = loggerFactory.CreateLogger<Startup>();
app.UseExceptionHandler(
options =>
{
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var errmsg = "An unexpected error has occured in API.";
var logDetails = new
{
CorrelationId = requestContext.CorrelationId,
Message = errmsg
};
logger.LogError(1001, ex.Error, "{#LogDetails}", logDetails);
await context.Response.WriteAsync(errmsg).ConfigureAwait(false);
}
});
});
app.UseMvc();
logger.LogInformation("Application has started in environment {0}", env.EnvironmentName);
}
Most of the time when there is any exception, Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware logs the exception as expected however, sometimes i see the following exception in the logs
2018-09-21 18:36:01.670 +00:00 [Error] An unhandled exception has
occurred: Duplicate type name within an assembly.
System.ArgumentException: Duplicate type name within an assembly.
at System.Reflection.Emit.ModuleBuilder.CheckTypeNameConflict(String
strTypeName, Type enclosingType) at
System.Reflection.Emit.AssemblyBuilderData.CheckTypeNameConflict(String
strTypeName, TypeBuilder enclosingType) at
System.Reflection.Emit.TypeBuilder.Init(String fullname,
TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder
module, PackingSize iPackingSize, Int32 iTypeSize, TypeBuilder
enclosingType) at
System.Reflection.Emit.ModuleBuilder.DefineType(String name,
TypeAttributes attr, Type parent, Type[] interfaces) at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyAssembly.DefineType(String
name, TypeAttributes attributes, Type baseType, Type[] interfaces)
at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyTypeEmitter.GenerateProxyTypeFromProperties(Type
sourceType, Type targetType, VerificationResult verificationResult)
at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyTypeEmitter.VerifyProxySupport(ProxyBuilderContext
context, Tuple2 key) at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyTypeEmitter.GetProxyType(ProxyTypeCache
cache, Type targetType, Type sourceType) at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyFactory.CreateProxy[TProxy](Object
obj) at Proxy_Method_From_<>f__AnonymousType03_To_Void
OnBeforeAction(Microsoft.AspNetCore.Http.HttpContext,
IRouteData)(Object , Object , IProxyFactory ) at
Microsoft.Extensions.DiagnosticAdapter.DiagnosticSourceAdapter.Write(String
diagnosticName, Object parameters) at
Microsoft.Extensions.DiagnosticAdapter.DiagnosticSourceAdapter.System.IObserver>.OnNext(KeyValuePair`2
value) at System.Diagnostics.DiagnosticListener.Write(String
name, Object value) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.d__6.MoveNext()
So looks like Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware its selft throwing exception while logging
Update 1
I have the following references. Not sure which reference is causing this issue.
Microsoft.ApplicationInsights.AspNetCore is 2.0 however the only options available for this package are 1.0.* or 2.*.*. I don't see this package has 1.1.* available
I'm running into an issue where LockRecursionException is thrown (occasionally) when sending a message in MassTransit via RabbitMq.
System.Threading.LockRecursionException: Write lock may not be acquired with read lock held. This pattern is prone to deadlocks
The exception is raised in the class MassTransit.Transports.DefaultConnectionPolicy, and it looks like the Execute method gets the read lock, runs a callback and always releases the read lock via a finally block. However, for whatever reason the callback raise a InvalidConnectionException and the code try to Reconnect(). The Reconnect() will try to get the write lock in TryEnterWriteLock and ends up with System.Threading.LockRecursionException as read lock is already being hold by the current thread. I'm unable to see how could that possibly happen given the Finally block should release the read lock, unless the ExitReadLock is not doing what it suppose to do.
I've included the full class from the MassTransit source code and full stack trace.
public class DefaultConnectionPolicy : ConnectionPolicy
{
readonly ConnectionHandler _connectionHandler;
readonly TimeSpan _reconnectDelay;
readonly ILog _log = Logger.Get(typeof(DefaultConnectionPolicy));
readonly ReaderWriterLockSlim _connectionLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public DefaultConnectionPolicy(ConnectionHandler connectionHandler)
{
_connectionHandler = connectionHandler;
_reconnectDelay = 10.Seconds();
}
public void Execute(Action callback)
{
try
{
try
{
// wait here so we can be sure that there is not a reconnect in progress
_connectionLock.EnterReadLock();
callback();
}
finally
{
_connectionLock.ExitReadLock();
}
}
catch (InvalidConnectionException ex)
{
_log.Warn("Invalid Connection when executing callback", ex.InnerException);
Reconnect();
if (_log.IsDebugEnabled)
{
_log.Debug("Retrying callback after reconnect.");
}
try
{
// wait here so we can be sure that there is not a reconnect in progress
_connectionLock.EnterReadLock();
callback();
}
finally
{
_connectionLock.ExitReadLock();
}
}
}
void Reconnect()
{
if (_connectionLock.TryEnterWriteLock((int)_reconnectDelay.TotalMilliseconds/2))
{
try
{
if (_log.IsDebugEnabled)
{
_log.Debug("Disconnecting connection handler.");
}
_connectionHandler.Disconnect();
if (_reconnectDelay > TimeSpan.Zero)
Thread.Sleep(_reconnectDelay);
if (_log.IsDebugEnabled)
{
_log.Debug("Re-connecting connection handler...");
}
_connectionHandler.Connect();
}
catch (Exception)
{
_log.Warn("Failed to reconnect, deferring to connection policy for reconnection");
_connectionHandler.ForceReconnect(_reconnectDelay);
}
finally
{
_connectionLock.ExitWriteLock();
}
}
else
{
try
{
_connectionLock.EnterReadLock();
if (_log.IsDebugEnabled)
{
_log.Debug("Waiting for reconnect in another thread.");
}
}
finally
{
_connectionLock.ExitReadLock();
}
}
}
}
And the full stack trace
An exception was thrown during Send ---> System.Threading.LockRecursionException: Write lock may not be acquired with read lock held. This pattern is prone to deadlocks. Please ensure that read locks are released before taking a write lock. If an upgrade is necessary, use an upgrade lock in place of the read lock.
at System.Threading.ReaderWriterLockSlim.TryEnterWriteLockCore(TimeoutTracker timeout)
at System.Threading.ReaderWriterLockSlim.TryEnterWriteLock(TimeoutTracker timeout)
at MassTransit.Transports.DefaultConnectionPolicy.Reconnect() in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Transports\DefaultConnectionPolicy.cs:line 75
at MassTransit.Transports.DefaultConnectionPolicy.Execute(Action callback) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Transports\DefaultConnectionPolicy.cs:line 53
at MassTransit.Transports.ConnectionPolicyChainImpl.Next(Action callback) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Transports\ConnectionPolicyChainImpl.cs:line 49
at MassTransit.Transports.ConnectionHandlerImpl`1.Use(Action`1 callback) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Transports\ConnectionHandlerImpl.cs:line 86
at MassTransit.Transports.RabbitMq.OutboundRabbitMqTransport.Send(ISendContext context) in z:\Builds\work\4ed32a1c3fc3f594\src\Transports\MassTransit.Transports.RabbitMq\OutboundRabbitMqTransport.cs:line 51
at MassTransit.Transports.Transport.Send(ISendContext context) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Transports\Transport.cs:line 50
at MassTransit.Transports.Endpoint.Send[T](ISendContext`1 context) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Transports\Endpoint.cs:line 111
--- End of inner exception stack trace ---
at MassTransit.Transports.Endpoint.Send[T](ISendContext`1 context) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Transports\Endpoint.cs:line 117
at MassTransit.Pipeline.Sinks.EndpointMessageSink`1.<Enumerate>b__0(IBusPublishContext`1 x) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Pipeline\Sinks\EndpointMessageSink.cs:line 45
at MassTransit.Pipeline.Sinks.OutboundConvertMessageSink`1.<>c__DisplayClass2.<>c__DisplayClass4.<Enumerate>b__1(ISendContext x) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Pipeline\Sinks\OutboundConvertMessageSink.cs:line 36
at MassTransit.ServiceBus.Publish[T](T message, Action`1 contextCallback) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\ServiceBus.cs:line 180
--- End of inner exception stack trace ---
at MassTransit.ServiceBus.Publish[T](T message, Action`1 contextCallback) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\ServiceBus.cs:line 207
at MassTransit.Context.BusObjectPublisherImpl`1.Publish(IServiceBus bus, Object message, Action`1 contextCallback) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\Context\BusObjectPublisherImpl.cs:line 30
at MassTransit.ServiceBus.Publish(Object message, Type messageType, Action`1 contextCallback) in z:\Builds\work\4ed32a1c3fc3f594\src\MassTransit\ServiceBus.cs:line 244
at CollectionHouse.MassTransit.Messaging.MassTransitMessageBus.PublishImmediate(Object message)
at CollectionHouse.MassTransit.Services.MassTransitPublisher.Publish(Object message)
at CollectionHouse.MicroBus.EventBroadcast.MessageBroadcastHandler.<Handle>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Enexure.MicroBus.PipelineBuilder.<>c__DisplayClass7_0.<<GenerateNext>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at CollectionHouse.MicroBus.PipelineHandlers.LoggingHandler.<Handle>d__3.MoveNext()
I have occasional exception when reading / storing objects with Amazon S3 from asp.net application.
Exception says:
Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall. A blocking operation was interrupted by a call to WSACancelBlockingCall
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
Any ideas about how I can locate what is reason of this error?
here is my read function:
public Image GetImage(string fullKey, out string errorMessage)
{
errorMessage = null;
try
{
GetObjectResponse response = s3Client.GetObject(new GetObjectRequest()
{
BucketName = BucketName,
Key = fullKey,
Timeout = ImportTimeout
});
return Image.FromStream(response.ResponseStream);
}
catch (Exception e)
{
errorMessage = e.Message;
Log.Current.WriteError(e);
}
return null;
}
s3Client is initialised in constructor of this class:
s3Client = AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey);
According to aws documentation it is correct to wrap call to GetObject with using:
http://docs.amazonwebservices.com/sdkfornet/latest/apidocs/html/M_Amazon_S3_AmazonS3_GetObject.htm
This eliminates all exceptions related to GetObject method