asp.net-core-mvcasp.net-mvc-routing.net-8.0

CatchAll Url redirect to HomePage not working in .NET 8.0


I'm using .NET 8.0 and I've added this line of code so that when the url is not found it can go back to the homepage but it's not working. Got several non-informative errors. I might be getting a scoop in the ocean here.

But I do have the same setup in an old .NET version (the one with startup.cs) but it is working.

app.MapControllerRoute(
            name: "NotFound",
            pattern: "{**catchall}",
            defaults: new { controller = "Home", action = "Index"});

This is my HomeController:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Solution

  • You should use MapFallbackToController to implement this feature. Here is the sample code.

    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        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.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.MapFallbackToController("Index", "Home");
    
    app.Run();