Abhijeet Patel
Abhijeet Patel

Reputation: 6868

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));
    }
}

Upvotes: 9

Views: 27311

Answers (5)

Zeeshan Allauddin
Zeeshan Allauddin

Reputation: 71

A standard MVC application can have both MVC and Webapi support if you check both MVC and Webapi from the Create New Asp.net web application template.

You will need to do the following under RouteConfig.cs as your query is particular to MVC routes and not webapi ones:

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

   }
 }

Notice the line with "routes.MapMvcAttributeRoutes();" which provides attribute routes while the call to "routes.MapRoute(...)" should provide you with a conventional route to a default controller and action.

This is because attribute routing and conventional routing can be mixed. Hope that helps.

Upvotes: 1

Somad
Somad

Reputation: 53

Enable the attribute routing in your WebApiConfig class located in the App_Start folder by putting the following code:

using System.Web.Http;

namespace MarwakoService
{
      public static class WebApiConfig
      {
            public static void Register(HttpConfiguration config)
            {
                // Web API routes
                config.MapHttpAttributeRoutes();

               // Other Web API configuration not shown.
            }
       }
 }

You can combine with the convention-based attribute:

public static class WebApiConfig
{
     public static void Register(HttpConfiguration config)
     {
          // Attribute routing.
          config.MapHttpAttributeRoutes();

          // Convention-based routing.
          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
              );
     }
}

Now go to your global.asax class and add the following line of code:

GlobalConfiguration.Configure(WebApiConfig.Register);

Your HomeController is an MVC controller. Try creating an API controller(let's say a CustomersController) and add your route attributes as follows:

[RoutePrefix("api/Product")]
public class CustomersController : ApiController
{
    [Route("{customerName}/{customerID:int}/GetCreditCustomer")]
    public IEnumerable<uspSelectCreditCustomer> GetCreditCustomer(string customerName, int customerID)
    {
        ...
    }

Hope it helps

Upvotes: 1

Sajjan Sarkar
Sajjan Sarkar

Reputation: 4198

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

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

Upvotes: 5

Pete Klein
Pete Klein

Reputation: 700

You need to install AttributeRouting (ASP.NET MVC) alongside AttributeRouting (ASP.NET Web API) that you have already installed.

The MVC and Web API packages are complimentary packages. Both dependent on the AttributeRouting.Core.* packages. AR for MVC is for routes on Controller methods; AR for Web API is for routes on ApiController methods.

Upvotes: 1

Kiran
Kiran

Reputation: 57939

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.

Upvotes: 9

Related Questions