I have to upgrade an ASP.NET Core Web API from .NET 6.0 to .NET 8.0. From Visual Studio installed, I installed .NET SDK 8.0.0 (X64) on my local machine. I installed upgrade assistant and upgraded to .NET 8.0.
My .csproj
file shows TargetFramework 8.0 now.
Below is my code
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
In Program.cs
at CreateHostBuilder(args)
, I get an error
System.InvalidOperationException
System.InvalidOperationException
HResult=0x80131509
Message=Multiple constructors accepting all given argument types have been found in type 'AspNetCoreApi.Startup'. There should only be one applicable constructor.
Source=Microsoft.Extensions.DependencyInjection.Abstractions
StackTrace:
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.TryFindMatchingConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& parameterMap)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& matchingParameterMap)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass7_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.InitializeServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at AspNetCoreApi.Program.Main(String[] args) in C:\CDHS\cdhs-kronos-dim-api\src\AspNetCoreApi\Program.cs:line 10
There should only be one applicable constructor.
Source=Microsoft.Extensions.DependencyInjection.Abstractions
StackTrace:
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.TryFindMatchingConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& parameterMap)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& matchingParameterMap)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass7_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.InitializeServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at AspNetCoreApi.Program.Main(String[] args) in C:\xxxxx\AspNetCoreApi\Program.cs:line 10
Below is my Startup.cs
file. I also upgraded the Nuget packages. No compile time error but I am getting this error in Program.cs
file at run time.
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment env)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllersWithViews();
services.AddRazorPages();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddScoped<IUserService, UserService>();
//services.AddScoped<IXmlRepository, XmlRepository>();
services.AddScoped<IKronosCppsRepository, KronosCppsRepository>();
services.AddScoped<IHrisRepository, HrisRepository>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IHrisIdentityRepository, HrisIdentityRepository>();
services.AddSingleton<IConfiguration>(Configuration);
services.AddScoped<IFileHelpers, FileHelpers>();
services.AddTransient<ViewModels.PingIdTester.RadiusClient>();
KronosCppsDbContext.ConnectionString = Configuration["Data:AspNetCoreApi:ConnectionStrings:KronosCppsConnectionString"];
services.AddDbContext<KronosCppsDbContext>();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new KronosCppsMappingProfile());
cfg.AddProfile(new HRISMappingProfile());
});
var mapper = config.CreateMapper();
services.AddAutoMapper(typeof(Startup));
services.AddSingleton(mapper);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
.AddCookie(options =>)
{
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.LoginPath = "/Account/Login?ReturnUrl=%2F";
options.AccessDeniedPath = "/Account/Login?ReturnUrl=%2F";
options.Events.OnRedirectToLogout = cxt => System.Threading.Tasks.Task.CompletedTask;
})
.AddJwtBearer("Bearer", options =>
{
options.Audience = "Other";
options.Authority = "";
options.ForwardAuthenticate = JwtBearerDefaults.AuthenticationScheme;
options.ClaimsIssuer = "Self";
options.IncludeErrorDetails = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key
};
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
//c.Response.StatusCode = 403;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync("Forbidden");
},
OnTokenValidated = ctx =>
{
ctx.Success();
return System.Threading.Tasks.Task.CompletedTask;
}
};
})
;
services.AddAuthorization(auth =>
{
auth.AddPolicy("Cookie, Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser()
.Build());
});
services.ConfigureApplicationCookie(options =>
{
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.Name = ".AspNetCore.Cookies";
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
// added different min loglevel for dev and staging
if (env.IsDevelopment() || env.EnvironmentName.Equals("local", StringComparison.OrdinalIgnoreCase))
{
loggerFactory.AddContext(LogLevel.Debug);
}
else if (env.IsStaging())
{
loggerFactory.AddContext(LogLevel.Information);
}
else // producton
{
loggerFactory.AddContext(LogLevel.Error);
}
loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
});
if (env.IsDevelopment() || env.EnvironmentName.Equals("local", StringComparison.OrdinalIgnoreCase))
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware<JwtMiddleware>();
app.UseHttpsRedirection();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseStatusCodePages();
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = context =>
{
var headers = context.Context.Response.GetTypedHeaders();
headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromDays(30),
};
}
});
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
//endpoints.MapRazorPages();
});
}
I removed the extra constructor
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
And got rid of this error.