In ASP.NET Core, from within a page or a controller, how can I check if that page or controller is the home page of the website? By "home page", I mean the controller or page you get when you enter just the root of the website, like "www.mysite.com/".
I'm aware that I can get the RouteData
and use its Values
property to get the current page or controller, like string? currentPage = RouteData.Values["page"] as string
and then check if currentPage == "/Index"
. However, what if custom route conventions specify a different name for the home page instead of the default "/Index" page or "/Home" controller?
In short, how can I make a reliable method like the hypothetical IsHome()
method, that tells me if I'm in the home page of the website, independently of whether I'm using MVC controllers or Razor pages?
You can inject the HttpContextAccessor and access the "controller" and "action" names using HttpContext.Request.RouteValues
HttpContext.Request.RouteValues
Count = 2
[0]: {[action, Index]}
[1]: {[controller, Home]}
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
public static class HomeHelper
{
public static bool IsHome(string controller, string action)
{
// customize the logic depending on which you want is the home
return (controller.toLower() == "home" && action.toLower() == "index")
}
}
public class HomeController : ControllerBase
{
private readonly IHttpContextAccessor _contextAccessor;
public HomeController(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
public IActionResult Index()
{
var controllerName = _contextAccessor.HttpContext.Request.RouteValues["controller"];
var actionName = _context.Accessor.HttpContext.Request.RouteValues["action"];
// this will return true
var isHome = HomeHelper.IsHome(controllerName, actionName);
return Content("");
}
}
The default route your project is indicated in;
Project > Properties > launchSettings.json
then look for launchUrl
You can also indicate another default route or fallback by specifying in your Program.cs; app.MapFallbackToController("Index", "Home");