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 });
}
}
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 });
}
}
Share
Improve this question
edited Mar 29 at 7:31
marc_s
756k184 gold badges1.4k silver badges1.5k bronze badges
asked Mar 28 at 16:06
choopauchoopau
2,4095 gold badges26 silver badges30 bronze badges
1 Answer
Reset to default 1You 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();