.NET Core SignalR 3.0 Exception - asp.net-core

NOTE: This is SignalR for .NET Core 3.
I saw a couple of other stackoverflow suggestions (similar but not exact) for the applicationUrl modification which I have tried. I am getting:
Unhandled exception. System.InvalidOperationException: A path base can only be configured using IApplicationBuilder.UsePathBase().
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.ParseAddress(String address, Boolean& https)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func2 createBinding)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication1 application, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
at cRioSaturnSignalRHub.Program.RunDefaultWebHostBuilder(String[] args, IConfigurationRoot config) in C:\Workspace\software\DataTier\dotNetCore\v3.x\Daemons\cRioSaturnSignalRHub\cRioSaturnSignalRHub\Program.cs:line 83
at cRioSaturnSignalRHub.Program.RunProcess(String[] args) in C:\Workspace\software\DataTier\dotNetCore\v3.x\Daemons\cRioSaturnSignalRHub\cRioSaturnSignalRHub\Program.cs:line 50
at cRioSaturnSignalRHub.Program.Main(String[] args) in C:\Workspace\software\DataTier\dotNetCore\v3.x\Daemons\cRioSaturnSignalRHub\cRioSaturnSignalRHub\Program.cs:line 27
The launch settings have applicationUrl = "http://localhost:5000" & the endpoint name is not on it as suggested in other stackoverflow related issue.
Any suggestions?

The problem is not at all related to the applicationUrl. Instead I tried the EnvironmentalVariables approach with the ASPNETCORE_URLS="http://*:5000" To do this I added .AddEnvironmentVariables() with the ConfigurationBuilder. & with WebHost.CreateDefaultBuilder(), I added .UseConfiguration(config). After this little change everything works when I publish & run.

Related

.NET Core issue: System.OperationCanceledException when hosted in IIS

My program.cs file in .NET Core 3.1 is like this I am creating web API in .net core but I am getting this error when hosted on server in IIS. API is working fine when hosted locally.
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config")).GetLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog();
}
System.OperationCanceledException: at program.cs error
I am getting this error with stack trace like:
Description: The process was terminated due to an unhandled exception.
Exception Info: System.OperationCanceledException: The operation was canceled.
at System.Threading.CancellationToken.ThrowOperationCanceledException()
at System.Threading.CancellationToken.ThrowIfCancellationRequested()
at Microsoft.Extensions.Hosting.Internal.Host.StopAsync(CancellationToken
cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.WaitForShutdownAsync(IHost
host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost
host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost
host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost
host)
What is wrong here?
I am experiencing the same error, and I was trying to see what might cause it.
I came across this link with the same issue
and the thing that jumped out at me was the "non-graceful shutdown". To test, I recycled the application website on IIS, which did not trigger the error. I then tried turning off the app pool via IIS, and DID trigger the exception.
This leads me to believe it has something to do with a task running inside the application that is cut short when the non-graceful shutdown occurs.
In my case, I have a HostedService running in the background of my application, do you have something similar in yours?

IdentityServer4, WindowsCryptographicException: The system cannot find the file specified

I create an IdentityServer4 project with several client apps. I use a self-signed certificate file my_certificate.pfx to generate login token. It works fine on localhost.
However, it does not work when employing it to a shared web hosting server.
The app that hosts the IdentityServer4 works fine, indicating that the server app can access the certificate file. However, it generates the following error when trying to log in from a client app:
WindowsCryptographicException: The system cannot find the file specified.
System.Security.Cryptography.CngKey.Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
System.Security.Cryptography.CngKey.Open(string keyName, CngProvider provider)
Internal.Cryptography.Pal.CertificatePal.GetPrivateKey<T>(Func<CspParameters, T> createCsp, Func<CngKey, T> createCng)
Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()
Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKeyStatus()
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.FoundPrivateKey(SecurityKey key)
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures, CryptoProviderFactory cryptoProviderFactory)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, string algorithm)
Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(string input, SigningCredentials signingCredentials)
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt)
IdentityServer4.Services.DefaultTokenCreationService.CreateTokenAsync(Token token)
IdentityServer4.Services.DefaultTokenService.CreateSecurityTokenAsync(Token token)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request, string authorizationCode)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateHybridFlowResponseAsync(ValidatedAuthorizeRequest request)
IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateResponseAsync(ValidatedAuthorizeRequest request)
IdentityServer4.Endpoints.AuthorizeEndpointBase.ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, ConsentResponse consent)
IdentityServer4.Endpoints.AuthorizeEndpoint.ProcessAsync(HttpContext context)
IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
How to make the client app works?
Thanks
I ran into this when setting up IdentityServer on AWS ElasticBeanstalk infrastructure and using a local file, rather than the certificate store - however the solution in my case is the same. I found that the app pools on the EC2 instances did not have Load User Profile set true. When set, the permissions model changes and allows the process to load in the cert. You can enable through the IIS management UI on the app pool details, or use a version of the script below.
Import-Module WebAdministration
Set-ItemProperty "IIS:\AppPools\DefaultAppPool" -Name "processModel.loadUserProfile" -Value "True"

How to Solve Redis Multiplexer in ASP.NET Core Problem

I my dotnet core project i am using redis for caching. In work fine in local,but i am getting following error in ubuntu server
Error
StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketClosed on PING
at StackExchange.Redis.ConnectionMultiplexer.ConnectAsync(String configuration, TextWriter log) in c:\code\StackExchange.Redis\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:line 799
at Microsoft.Extensions.Caching.Redis.RedisCache.ConnectAsync(CancellationToken token)
at Microsoft.Extensions.Caching.Redis.RedisCache.GetAndRefreshAsync(String key, Boolean getData, CancellationToken token)
at Microsoft.Extensions.Caching.Redis.RedisCache.RefreshAsync(String key, CancellationToken token)
at Microsoft.AspNetCore.Session.DistributedSession.CommitAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
Unhandled Exception: StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketClosed on PING
at StackExchange.Redis.ConnectionMultiplexer.ConnectAsync(String configuration, TextWriter log) in c:\code\StackExchange.Redis\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:line 799
at Microsoft.Extensions.Caching.Redis.RedisCache.ConnectAsync(CancellationToken token)
at Microsoft.Extensions.Caching.Redis.RedisCache.SetAsync(String key, Byte[] value, DistributedCacheEntryOptions options, CancellationToken token)
at otpservice.Helper.HOtp.GenerateOtp(String userid) in D:\SampleHelper\HOtp.cs:line 39
at otpservice.Controllers.OtpController.Otp(Object userData) in D:\Sample\Controllers\OtpController.cs:line 41
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ThreadPoolWorkQueue.Dispatch()
Aborted
ConfigureService method in Startup.cs
services.AddDistributedRedisCache(options =>
{
options.InstanceName = "Sample";
//For the Server i am using IP Instead of localhost
options.Configuration = "localhost";
});
During caching in my Code
var cache = new RedisCache(new RedisCacheOptions
{
//For the Server i am using IP Instead of localhost
Configuration = "localhost",
});
How to Solve the error.
Thank you...

ServiceFabric: Service does not exist during deployment

I have an existing system using service fabric. Everything is fine except during a service publish the service is unavailable and any resolutions return an error.
This is expected however it would be nice if during this time instead the calls just waited or timedout. During this time my error logs will sometimes fill up with 200K lines of the same error.
I want some code like the following however where would it go?
public async Task Execute(Func<Task> action)
{
try
{
action()
.ConfigureAwait(false);
}
catch (FabricServiceNotFoundException ex)
{
await Task.Delay(TimeSpan.FromSeconds(??))
.ConfigureAwait(false);
action()
.ConfigureAwait(false);
}
}
Error:
System.Fabric.FabricServiceNotFoundException: Service does not exist. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80071BCD
at System.Fabric.Interop.NativeClient.IFabricServiceManagementClient6.EndResolveServicePartition(IFabricAsyncOperationContext context)
at System.Fabric.FabricClient.ServiceManagementClient.ResolveServicePartitionEndWrapper(IFabricAsyncOperationContext context)
at System.Fabric.Interop.AsyncCallOutAdapter2`1.Finish(IFabricAsyncOperationContext context, Boolean expectedCompletedSynchronously)
--- End of inner exception stack trace ---
at Microsoft.ServiceFabric.Services.Client.ServicePartitionResolver.ResolveHelperAsync(Func`5 resolveFunc, ResolvedServicePartition previousRsp, TimeSpan resolveTimeout, TimeSpan maxRetryInterval, CancellationToken cancellationToken, Uri serviceUri)
at Microsoft.ServiceFabric.Services.Communication.Client.CommunicationClientFactoryBase`1.CreateClientWithRetriesAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, String listenerName, OperationRetrySettings retrySettings, Boolean doInitialResolve, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Communication.Client.CommunicationClientFactoryBase`1.GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplica, String listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.V2.FabricTransport.Client.FabricTransportServiceRemotingClientFactory.GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, String listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Communication.Client.ServicePartitionClient`1.GetCommunicationClientAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Communication.Client.ServicePartitionClient`1.InvokeWithRetryAsync[TResult](Func`2 func, CancellationToken cancellationToken, Type[] doNotRetryExceptionTypes)
at Microsoft.ServiceFabric.Services.Remoting.V2.Client.ServiceRemotingPartitionClient.InvokeAsync(IServiceRemotingRequestMessage remotingRequestMessage, String methodName, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.Builder.ProxyBase.InvokeAsyncV2(Int32 interfaceId, Int32 methodId, String methodName, IServiceRemotingRequestMessageBody requestMsgBodyValue, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.Builder.ProxyBase.ContinueWithResultV2[TRetval](Int32 interfaceId, Int32 methodId, Task`1 task)
As expected, Service Fabric have to shutdown the service to start the new version, this will cause a transient error like the one you've got.
By default, the Remoting APIs already have a retry logic built-in, from the docs:
The service proxy handles all failover exceptions for the service
partition it is created for. It re-resolves the endpoints if there are
failover exceptions (non-transient exceptions) and retries the call
with the correct endpoint. The number of retries for failover
exceptions is indefinite. If transient exceptions occur, the proxy
retries the call.
With that said, you should not require to add extra retry logic, maybe you should try adjust the OperationRetrySettings for a better handling of these retries.
If does not solve the problem, and you still want to add the logic in your code, the simplest way to handle it is using a transient-fault-handling library like Polly, something like below:
var policy = Policy
.Handle<FabricServiceNotFoundException>()
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(3)
});
policy.Execute(() => DoSomething());
In this sample, you do an exponential backoff between retries, if the number of calls is too big, I would recomend implement the circuit breaker approach instead.

RavenDB Embedded on Azure Websites - Access Denied

I get an Access denied message when I try to deploy my MVC4 site with an Embedded instance of RavenDB to the new Azure Websites preview feature. The site works fine locally.
Here is how I configure Raven:
//Initialize the RavenDB Data Store
Raven.Database.Server.NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8887);
var documentStore = new EmbeddableDocumentStore()
{
DataDirectory = "~\\App_Data",
UseEmbeddedHttpServer = true,
Configuration = { Port = 8887 }
};
documentStore.Initialize();
And here is the stack trace when I browse to the site:
Access is denied
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.NetworkInformation.NetworkInformationException: Access is denied
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NetworkInformationException (0x5): Access is denied]
System.Net.NetworkInformation.SystemIPGlobalProperties.GetAllTcpConnections() +1570717
System.Net.NetworkInformation.SystemIPGlobalProperties.GetActiveTcpListeners() +74
Raven.Database.Util.PortUtil.FindPort() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Util\PortUtil.cs:110
Raven.Database.Util.PortUtil.GetPort(String portStr) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Util\PortUtil.cs:44
Raven.Database.Config.InMemoryRavenConfiguration.Initialize() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Config\InMemoryRavenConfiguration.cs:170
Raven.Database.Config.RavenConfiguration.LoadConfigurationAndInitialize(IEnumerable`1 values) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Config\RavenConfiguration.cs:28
Raven.Database.Config.RavenConfiguration..ctor() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Config\RavenConfiguration.cs:17
Raven.Client.Embedded.EmbeddableDocumentStore.get_Configuration() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Client.Embedded\EmbeddableDocumentStore.cs:63
Raven.Client.Embedded.EmbeddableDocumentStore.set_DataDirectory(String value) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Client.Embedded\EmbeddableDocumentStore.cs:90
Solarity.DesignSearch.Website.Bootstrapper.BuildUnityContainer() in c:\a\src\Solarity.DesignSearch\Solarity.DesignSearch.Website\Bootstrapper.cs:35
Solarity.DesignSearch.Website.Bootstrapper.Initialise() in c:\a\src\Solarity.DesignSearch\Solarity.DesignSearch.Website\Bootstrapper.cs:20
Solarity.DesignSearch.Website.MvcApplication.Application_Start() in c:\a\src\Solarity.DesignSearch\Solarity.DesignSearch.Website\Global.asax.cs:23
[HttpException (0x80004005): Access is denied]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9859725
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Access is denied]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
I managed to get it to work, although it is not ideal. You may notice in my original post that I am setting the UseEmbeddedHttpServer = true. This is so that I can browse to http:[MyUrl]:8081 and get the RavendDB Management Studio so that I can browse my data. For some reason, RavenDB wants to do the same kind of port check when this property is set as it does when you set the Port setting to automatic (Port=*).
I believe that RavenDB may need a fix so that it honors the Port setting when UseEmbeddedHttpServer is True and also let you set the Configuration property of the EmbeddedDocumentStore upon creation.
But in the meantime, you can truly get your MVC4 site to work with an EmbeddedDocumentStore on Azure Websites simply by specifying a port. Also, you do indeed have to use the AppSettings configuration rather than setting the Configuration property of the EmbeddedDocumentStore upon creation (like I tried to do above). This post (stackoverflow.com/questions/11529159/) shows how to do it.
Unfortunately, I still haven't found a way to run the EmbeddedHttpServer so I can use the Raven Management Studio. If I figure out how, I will post a solution here.
Hi this was answered on RavenDb on Azure Websites - Access Denied
Basically you need to configure the port in Web.config