Search code examples
asp.netasp.net-mvcasp.net-web-apiattributerouting

Default attributing routing not working


I am working on a new project and i have decided to use attribute routing alone. This is my RouteConfig file:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        //routes.MapRoute(
        //    name: "Default",
        //    url: "{controller}/{action}",
        //    defaults: new { controller = "HomeController", action = "Index", id = UrlParameter.Optional }
        //);
    }

This is my controller:

[RoutePrefix("home")]
public class HomeController : Controller
{
    [Route]
    [Route("~/")]
    public ActionResult Index()
    {
        var status = HttpContext.User.Identity.IsAuthenticated;
        ViewBag.Title = "Home Page";

        return View();
    }

    [Route("test")]
    public ActionResult Test()
    {

        return View();
    }
}

I've realised that typically all my attributes are working but i want the Index method to run on application start. Say https://example.com and then the Index method is fired as if i entered the url https://example.com/home/index. I get a blank space when i do say https://example.com.

Can anyone please help me understand why i get a blank space and also how to set the default application start route using attribute routing? I've been surfing the internet for hours but i can't lay my hands on anything.


Solution

  • Try this:

    [RoutePrefix("home")]
    public class HomeController : Controller 
    {
        [Route("index")]
        [Route("~/", Name = "default")]
        public ActionResult Index()
        {
            ...
        }
    
        ...
    }