Search code examples
c#visual-studioasp.net-coreasp.net-core-mvcrazor-pages

ASP.NET Core default template project fails with HTTP ERROR 404 or Exception


I have a problem with ASP.NET Core MVC or Razor applaunch.json.

I use a default template to create a project with default settings:

  • ASP.Net Core Web App - Dot Net 6
  • ASP.Net Core Web App MVC - Dot Net 6

This is my applaunch.json:

{
    "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
            "applicationUrl": "http://localhost:18583",
            "sslPort": 44326
        }
    },
    "profiles": {
        "WebApplication12": {
            "commandName": "Project",
            "dotnetRunMessages": true,
            "launchBrowser": true,
            "applicationUrl": "https://localhost:7081;http://localhost:5081",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        },
        "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        }
    }
}

And program.cs :

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

After launch console shows that no problem with listening to ports :

Console after launch

But I get an exception for my ASP.NET Core MVC projects:

When running MVC projects

And I get 404 for Razor Pages:

When running Razor Page projects

All configurations are default template configurations.

Did anyone experience the same problem?


Solution

  • I solved the problem by using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package and adding the following service:

    For ASP.NET Core Razor template

    builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
    

    And for the MVC project template:

    builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
    

    The second solution is to use dotnet run watch either in Developer Power Shell or Command-Line.