1

For Asp.Net Core 3.1 projects, how do I remove the requirement to have /Home in the url for actions in the Home controller?

I tried decorating the controller with the attribute [Route("/")] but it does not work.

The start up configuration is the default from Visual Studio's template:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Old Geezer
  • 14,854
  • 31
  • 111
  • 198

1 Answers1

2

Add empty route templates to the controller and Index action:

[Route("")]
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

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

    [Route("")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("Privacy")]
    public IActionResult Privacy()
    {
        return View();
    }

    [Route("Error")]
    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
LazZiya
  • 5,286
  • 2
  • 24
  • 37
  • This works well for me. It even takes care of forming the correct urls in `asp-*` attributes. For example: `
    ` will generate this html: `
    `. If it just configuring the routes, I doubt if such things will be taken care of.
    – Old Geezer May 19 '20 at 13:50