Search code examples
c#visual-studioasp.net-coreasp.net-core-mvc.net-9.0

How to use MapStaticAssets if upgrading from .NET 8


In ASP.NET Core 9 MVC application after upgrading to .NET 9 in startup.cs file, this line

app.UseStaticFiles();

was replaced with:

 app.MapStaticAssets();

according to https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-9.0

This causes compile time error CS1929

'IApplicationBuilder' does not contain a definition for 'MapStaticAssets' and the best extension method overload 'StaticAssetsEndpointRouteBuilderExtensions.MapStaticAssets(IEndpointRouteBuilder, string?)' requires a receiver of type 'Microsoft.AspNetCore.Routing.IEndpointRouteBuilder'

How to use MapStaticAssets ?

Update

Target framework and packages are .NET 9. In startup.cs replacing

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)

with

public void Configure(WebApplication app, IWebHostEnvironment env, ILogger<Startup> logger)

removes compile error. However in this case runtime error

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Builder.WebApplication' has been registered.

occurs. How to fix this?

.NET 9 MVC application solution template does not contain starup.cs. Application uses ConfigureServices like

  public void ConfigureServices(IServiceCollection services)
  {
    services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(@"Keys")
      )
   ....

.NET 9 application template does not contain service configuration.


Solution

  • From .NET 6, the new application template uses the New Hosting Model, it will unify Startup.cs and Program.cs into a single Program.cs file and uses top-level statements to minimize the code required for an app. So we can add services and middleware in the Program.cs file like this:

    new hosting model

    More detail information, see:

    New hosting model

    Code samples migrated to the new minimal hosting model in ASP.NET Core 6.0

    If you want to convert the application to use Startup.cs and Program.cs file. In the new template application, you can add a Startup.cs file and refer to the following code:

    Program.cs file:

    public class Program
    {
        public static void Main(string[] args)
        {
    
            var builder = WebApplication.CreateBuilder(args);
    
            // Set up logging
            builder.Logging.ClearProviders();
            builder.Logging.AddConsole();
            builder.Logging.AddDebug();
    
            // Create a logger factory to pass to Startup
            using var loggerFactory = LoggerFactory.Create(logging =>
            {
                logging.AddConsole();
                logging.AddDebug();
            });
            var logger = loggerFactory.CreateLogger<Startup>();
    
            // Initialize Startup and configure services
            var startup = new Startup(builder.Configuration, logger);
            startup.ConfigureServices(builder.Services);
    
            var app = builder.Build();
    
            // Configure the middleware pipeline
            startup.Configure(app, app.Environment);
    
            app.Run();
        }
    }
    

    Startup.cs file:

    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    using WebApplication2.Data;
    
    namespace WebApplication2
    {
        public class Startup
        {
            private readonly IConfiguration Configuration;
            private readonly ILogger<Startup> _logger;
            public Startup(IConfiguration configuration, ILogger<Startup> logger)
            {
                Configuration = configuration;
                _logger = logger;
    
                // Log a message during startup initialization
                _logger.LogInformation("Startup initialized.");
            }
            public void ConfigureServices(IServiceCollection services)
            {
                _logger.LogInformation("Configuring services...");
                services.AddControllersWithViews();
                services.AddRazorPages();
                // Add other services here
    
                //// Add services to the container.
                var connectionString = Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(connectionString));
                services.AddDatabaseDeveloperPageExceptionFilter();
    
                services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                    .AddEntityFrameworkStores<ApplicationDbContext>();
                services.AddControllersWithViews();
            }
    
            public void Configure(WebApplication app, IWebHostEnvironment env)
            {
                _logger.LogInformation("Configuring middleware...");
                // Configure the HTTP request pipeline.
                if (env.IsDevelopment())
                {
                    app.UseMigrationsEndPoint();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.MapStaticAssets();
                app.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}")
                    .WithStaticAssets();
                app.MapRazorPages()
                   .WithStaticAssets();
            }
        }
    }