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?
Related
I'm new in Elsa Workflow. I try to set up a simple Hello World REST API following the steps in the URL below:
https://elsa-workflows.github.io/elsa-core/docs/next/quickstarts/quickstarts-aspnetcore-hello-world
However, when I set up the project using dotnet, no Startup.cs is found. I check my dotnet version using dotnet --version, it shows 7.0.100. I search the web, it said that Startup.cs is removed and no longer required in Web App, starting from .Net 6.0 onwards.
My question is:
Do I need to install the old .Net Core 3.1 to make Elsa work?
If not, how do I set up a simple Elsa workflow using .Net 7.0?
I've tried to move the code in Startup.cs into Program.cs as below:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddElsa(options => options
.AddHttpActivities()
.AddWorkflow<ElsaQuickstarts.WebApp.HelloWorld.HelloWorld>());
var app = builder.Build();
app.Run();
But when I build the program and run, it gives the following error:
Unhandled exception. System.InvalidOperationException: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAuthorization' in the application startup code.
at Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.VerifyServicesRegistered(IApplicationBuilder app)
at Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.UseAuthorization(IApplicationBuilder app)
at Microsoft.AspNetCore.Builder.WebApplicationBuilder.ConfigureApplication(WebHostBuilderContext context, IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
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)
at Program.<Main>$(String[] args) in C:\Git\ElsaQuickstarts.WebApp.HelloWorld\Program.cs:line 10
Add AddAuthorization to the services and call UseHttpActivities to add Elsa's middleware to handle HTTP requests to workflows:
var builder = WebApplication.CreateBuilder(args);
builder.Services
// ...
.AddAuthorization();
var app = builder.Build();
app.UseHttpActivities();
app.Run();
I've been hovering around this issue for quite some time now and still haven't found an answer, nor another post dealing with the same problem.
I have published a .net 5.0 Website and everything works fine if I run dotnet inside the same published folder. in this folder I also have a file called appsettings.json with all the configuration needed by the application ie:
+ path
+ to
+ karinapi
- MinosIT.Karin.API.dll
- appsettings.json
When I run dotnet inside the folder, everything works fine and the settings are read without any problem:
cd /path/to/karinapi
dotnet MinosIT.Karin.API.dll
The result is ok ie:
user#machine$ dotnet MinosIT.Karin.API.dll
info: MinosIT.Karin.API.Program[0]
Inicializando migraciĆ³n
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
Verificando migraci+on
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
Checking whether journal table exists..
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
Fetching list of already executed scripts.
info: MinosIT.Karin.API.Program[0]
finalizando migraciĆ³n
but when I try to follow this guide:
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-5.0
it says that you have to create a service and run the app like this
/usr/bin/dotnet /path/to/karinapi/MinosIT.Karin.API.dll
The problem is that when I try to run my app while being outside the publish folder, dotnet doesn't seem to find appsettings.json file ie:
user#mymachine$ pwd
/path/to/
user#mymachine$ /user/bin/dotnet /path/to/karinapi/MinosIT.Karin.API.dll
Application fails and throws this error:
user#mymachine$ dotnet karinapi/MinosIT.Karin.API.dll
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'implementationInstance')
at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton[TService](IServiceCollection services, TService implementationInstance)
at MinosIT.Karin.API.Startup.ConfigureServices(IServiceCollection services) in D:\Minos IT\Karin\MinosIT.Karin\BackEnd\MinosIT.Karin.api\Startup.cs:line 72
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) in /_/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs:line 399
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.g__Startup|0(IServiceCollection serviceCollection)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.b__0(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
I'm using Microsoft.Extensions.Configuration.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public IConfiguration Configuration { get; }
...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
and inside StartUp.ConfigureServices I'm using:
var connectionString = Configuration.GetConnectionString("ConnectionStringName");
var section = Configuration.GetSection("CustomSection").Get<CustomConfiguration>();
When I debug, my code via logging I understand that the problem might be the ASP.NET Core doesn't know where to read appsettings.json, I have looked at dotnet cli docs, environment variables, other configuration types and I can't seem to find the problem. I really don't know what else to look for, any guidance or help will be appreciated.
Thanks in advance for your help.
Found a solution, I'm posting here in case someone else is struggling with the same error:
inside Program.cs I changed from:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}
);
to
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var assembly = Assembly.GetExecutingAssembly();
var currentPath = System.IO.Path.GetDirectoryName(assembly.Location);
config.SetBasePath(currentPath);
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}
);
In version 3.0 and up of Net Core a web application can be setup this way:
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration(config =>
{
var settingsFile = Environment.GetEnvironmentVariable("APP_SETTINGS");
if (!string.IsNullOrWhiteSpace(settingsFile))
{
config.AddJsonFile(settingsFile, optional: false);
}
});
webBuilder.UseStartup<Startup>();
});
While using CreateDefaultBuilder very convenient and abstracts a lot of boilerplate, it also forcibly enables IIS integrations for the app. In my case, I want to run the app using raw Kestrel without IIS proxying requests.
Is my only choice to extract all the boilerplate from CreateDefaultBuilder() if I want to not use the IIS integrations, or can I somehow overwrite this? I've been studying the source code for this methods and I can't see a way to solve this.
Do you know of an easier method to achieve this other than having to write all the setup code myself?
I have an application in ASP.NET Core 2.2 which requires Windows Authentication.
To have a full development environment, we use HTTP.sys because it allows us to have full NTLM support with the watcher:
dotnet watch run
The problem occurrs, when we deploy into IIS 10.0
Startup file is configured as following:
services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
services.Configure<IISOptions>(options =>
{
options.AutomaticAuthentication = true;
});
Program is configured as following:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost
.CreateDefaultBuilder(args)
.UseIISIntegration()
.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
})
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console());
}
On local development everything works as expected.
When we deploy, we have the following errors:
If we set the web.config hostingModel="InProcess"
2019-10-16 17:03:14.320 +02:00 [Fatal] Application startup exception
System.InvalidOperationException: Application is running inside IIS process but is not configured to use IIS server.
at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
If we remove it, so Out Process:
2019-10-16 17:10:38.151 +02:00 [Fatal] Application startup exception
System.InvalidOperationException: Scheme already exists: Windows
at Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider.AddScheme(AuthenticationScheme scheme)
at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware..ctor(RequestDelegate next, ILoggerFactory loggerFactory, IOptions`1 options, String pairingToken, Boolean isWebsocketsSupported, IAuthenticationSchemeProvider authentication, IApplicationLifetime applicationLifetime)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_0.<UseMiddleware>b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
As per the hangfire documentation
Starting from Hangfire 1.3.0, you are not required to do anything, if
your application already uses one of the following libraries through
the reflection (so that Hangfire itself does not depend on any of
them). Logging implementation is automatically chosen by checking for
the presence of corresponding types in the order shown below.
Serilog
NLog
Log4Net
EntLib
Logging
Loupe
Elmah
I have ASP.NET Core 2.0 application that is using Serilog like below
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseApplicationInsights()
.UseUrls("http://*:40006")
.ConfigureAppConfiguration((hostingContext, config) =>
{
// removed for bravity
})
.ConfigureLogging((hostingContext, logging) =>
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(hostingContext.Configuration)
.CreateLogger();
logging.AddSerilog();
})
.Build();
}
The application is configured to use Hangfire. During background job processing if there is any exception occurs, Hangfire re-tries the job 10 times with increasing delay as expected, and it shows the exceptions in dashboard.
Issue
The Hangfire dashboard shows the exception on UI however it does not log the exception into configured Serilog sink.
Note: The Hangfire dashboard shows exception but it formats the exception see here which hides critical information about the exception.
I think if it logs the exception, Serilog logger would log the complete exception.
I had the same issue with the latest Hangfire version using .NET Core 3.1.
The solution was to call the UseSerilogLogProvider() method of IGlobalConfiguration in StartUp.cs.
For example:
GlobalConfiguration.Configuration.UseSerilogLogProvider();
or
services.AddHangfire(configuration => configuration
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSerilogLogProvider());
Normally this call shouldn't be needed but there are some cases where automatic wiring isn't working (an example would be referencing multiple logging providers). You can read more about this in the official Hangfire documentation: Configure Logging