12

I'm using attribute routing from ASP.NET 5 RC, included in the Visual Studio 2013 RC release.

I'd like for the root path, /, to lead to the canonical /Home/Index path, but I can't find a way to do this with just attribute routes. Is it possible, and if not, how would I do it if I'm also using OWIN SelfHost? In other words, I'm setting up my own HttpConfiguration class manually in the WebApp.Start<T> method (where T has a Configure(IAppBuilder) method invoked at startup) and not going through the RouteTable.Routes object. Or should I be going through the RouteTable.Routes object? I haven't had much luck with that when I tried it...

EDIT: Here's what I've tried so far:

// normal Web API attribute routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
   name: "DefaultWeb",
   routeTemplate: "{controller}/{action}",
   defaults: new { controller = "Home", action = "Index" }
);

The second try below looks a little dubious, since it's not clear how my HttpConfiguration object is related to the static RouteTable.Routes object:

// normal Web API attribute routes
config.MapHttpAttributeRoutes();

RouteTable.Routes.MapRoute(
   name: "DefaultWeb",
   url: "{controller}/{action}",
   defaults: new { controller = "Home", action = "Index" }
);
gzak
  • 3,908
  • 6
  • 33
  • 56

2 Answers2

29

You can set the default route for the app like this:

    [Route("~/", Name = "default")]
    public ActionResult Index() {
        return View();
    }
Jared
  • 5,840
  • 5
  • 49
  • 83
Jay Douglass
  • 4,828
  • 2
  • 27
  • 19
  • I got "The current request is ambiguous between the following action methods: ..." when trying this. I added [RoutePrefix( "home" )] to my controller definition and changed [Route] to [Route( "index" )] to remove the ambiguity. Both / (default) and /home/index now work. – Anthony Longano Sep 08 '14 at 15:30
  • 2
    I also got the ambiguous error, and the ambiguity was pointing both to the same controller. I removed the "[Route]" shown above and now it works. – HK1 Jun 25 '15 at 13:16
1

For anyone who is using .NET Core 1.x, you'll need to do this as well as use Jay's answer above.

In your Startup.cs file, add this to your Configure method.

app.UseMvcWithDefaultRoute();

Then, any controller action you want as the default, put the attribute [Route("", Name = "default")]

Nick George
  • 327
  • 3
  • 9