Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify default controller/action route in WebAPI using AttributeRouting

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));
    }
}
like image 530
Abhijeet Patel Avatar asked Apr 28 '13 17:04

Abhijeet Patel


People also ask

How do I specify a route in Web API?

The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config. MapHttpAttributeRoutes() method.

In which method we have the default route configured for your Web API project?

The default route template for Web API is "api/{controller}/{id}".

How would you setup the default route using endpoints?

UseEndpoints(endpoints => { endpoints. MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); Inside the call to UseEndpoints() , we use the MapControllerRoute() method to create a route by giving the name default .


1 Answers

This worked for me. Add this to Register() in WebApiConfig class

config.Routes.MapHttpRoute(
                name: "AppLaunch",
                routeTemplate: "",
                defaults: new
                {
                    controller = "Home",
                    action = "Get"
                }
           );
like image 173
Sajjan Sarkar Avatar answered Sep 28 '22 02:09

Sajjan Sarkar