0

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.

Willie
  • 239
  • 3
  • 15

2 Answers2

2

In your case you should still set a default route. That way the site knows where to start. From there everything else should work as you intended.

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

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{action}",
        defaults: new { controller = "Home", action = "Index" }
    );
}

Here is my Home Controller.

public class HomeController : FrontOfficeControllerBase {
    public HomeController() {
    }

    public ActionResult Index() {
        ...
        return View();
    }
}

Other than that this keeps my route config clean as I use attribute routing everywhere else.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • I receive an exception saying i can't start a route with "/". How do i fix that? The exception was caught on the url: "/" part – Willie Feb 05 '16 at 12:06
  • I removed it yet i got a blank page. Should i maintain attribute on the Index action method. Or since I'm using the convention-based routing, i should get that route off? – Willie Feb 05 '16 at 12:09
  • Can you please post both your RouteConfig.cs file and your controller for the hello world test you did so i can compare? – Willie Feb 05 '16 at 12:26
1

Try this:

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

    ...
}
Frank Fajardo
  • 7,034
  • 1
  • 29
  • 47