Specify default controller/action route in WebAPI using AttributeRouting

Abhijeet Patel picture Abhijeet Patel · Apr 28, 2013 · Viewed 23.5k times · Source

How does one set the default controller to use when using AttributeRouting instead of the default RouteConfiguration that WebAPI uses. i.e. get rid of the commented code section since this is redundant when using AttribteRouting

    public class RouteConfig
    {
       public static void RegisterRoutes(RouteCollection routes)
       {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //routes.MapRoute(
        //    name: "Default",
        //    url: "{controller}/{action}/{id}",
        //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        //);

       }
     }

If I comment the section above and try to run the webapi app, I get the following error since there is no default Home controller/action defined. HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

How can I specify the route via Attribute routing for the Home controller/action?

EDIT: Code Sample:

 public class HomeController : Controller
{
    [GET("")]
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Help()
    {
        var explorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
        return View(new ApiModel(explorer));
    }
}

Answer

Kiran Challa picture Kiran Challa · Apr 29, 2013

Have you tried the following:

//[RoutePrefix("")]
public class HomeController : Controller
{
    [GET("")]
    public ActionResult Index()
    {
        return View();
    }
}

This will add a route in the collection with url template as "" and defaults for controller and action to be "Home" and "Index" respectively.